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/lldb-python.h" 11 12 #include "lldb/Target/Process.h" 13 14 #include "lldb/lldb-private-log.h" 15 16 #include "lldb/Breakpoint/StoppointCallbackContext.h" 17 #include "lldb/Breakpoint/BreakpointLocation.h" 18 #include "lldb/Core/Event.h" 19 #include "lldb/Core/ConnectionFileDescriptor.h" 20 #include "lldb/Core/Debugger.h" 21 #include "lldb/Core/Log.h" 22 #include "lldb/Core/Module.h" 23 #include "lldb/Symbol/Symbol.h" 24 #include "lldb/Core/PluginManager.h" 25 #include "lldb/Core/State.h" 26 #include "lldb/Core/StreamFile.h" 27 #include "lldb/Expression/ClangUserExpression.h" 28 #include "lldb/Interpreter/CommandInterpreter.h" 29 #include "lldb/Host/Host.h" 30 #include "lldb/Host/Pipe.h" 31 #include "lldb/Host/Terminal.h" 32 #include "lldb/Target/ABI.h" 33 #include "lldb/Target/DynamicLoader.h" 34 #include "lldb/Target/JITLoader.h" 35 #include "lldb/Target/OperatingSystem.h" 36 #include "lldb/Target/LanguageRuntime.h" 37 #include "lldb/Target/CPPLanguageRuntime.h" 38 #include "lldb/Target/ObjCLanguageRuntime.h" 39 #include "lldb/Target/Platform.h" 40 #include "lldb/Target/RegisterContext.h" 41 #include "lldb/Target/StopInfo.h" 42 #include "lldb/Target/SystemRuntime.h" 43 #include "lldb/Target/Target.h" 44 #include "lldb/Target/TargetList.h" 45 #include "lldb/Target/Thread.h" 46 #include "lldb/Target/ThreadPlan.h" 47 #include "lldb/Target/ThreadPlanBase.h" 48 #include "Plugins/Process/Utility/InferiorCallPOSIX.h" 49 50 using namespace lldb; 51 using namespace lldb_private; 52 53 54 // Comment out line below to disable memory caching, overriding the process setting 55 // target.process.disable-memory-cache 56 #define ENABLE_MEMORY_CACHING 57 58 #ifdef ENABLE_MEMORY_CACHING 59 #define DISABLE_MEM_CACHE_DEFAULT false 60 #else 61 #define DISABLE_MEM_CACHE_DEFAULT true 62 #endif 63 64 class ProcessOptionValueProperties : public OptionValueProperties 65 { 66 public: 67 ProcessOptionValueProperties (const ConstString &name) : 68 OptionValueProperties (name) 69 { 70 } 71 72 // This constructor is used when creating ProcessOptionValueProperties when it 73 // is part of a new lldb_private::Process instance. It will copy all current 74 // global property values as needed 75 ProcessOptionValueProperties (ProcessProperties *global_properties) : 76 OptionValueProperties(*global_properties->GetValueProperties()) 77 { 78 } 79 80 virtual const Property * 81 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const 82 { 83 // When getting the value for a key from the process options, we will always 84 // try and grab the setting from the current process if there is one. Else we just 85 // use the one from this instance. 86 if (exe_ctx) 87 { 88 Process *process = exe_ctx->GetProcessPtr(); 89 if (process) 90 { 91 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get()); 92 if (this != instance_properties) 93 return instance_properties->ProtectedGetPropertyAtIndex (idx); 94 } 95 } 96 return ProtectedGetPropertyAtIndex (idx); 97 } 98 }; 99 100 static PropertyDefinition 101 g_properties[] = 102 { 103 { "disable-memory-cache" , OptionValue::eTypeBoolean, false, DISABLE_MEM_CACHE_DEFAULT, NULL, NULL, "Disable reading and caching of memory in fixed-size units." }, 104 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. " 105 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" }, 106 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." }, 107 { "unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, errors in expression evaluation will unwind the stack back to the state before the call." }, 108 { "python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, NULL, NULL, "A path to a python OS plug-in module file that contains a OperatingSystemPlugIn class." }, 109 { "stop-on-sharedlibrary-events" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, stop when a shared library is loaded or unloaded." }, 110 { "detach-keeps-stopped" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, detach will attempt to keep the process stopped." }, 111 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL } 112 }; 113 114 enum { 115 ePropertyDisableMemCache, 116 ePropertyExtraStartCommand, 117 ePropertyIgnoreBreakpointsInExpressions, 118 ePropertyUnwindOnErrorInExpressions, 119 ePropertyPythonOSPluginPath, 120 ePropertyStopOnSharedLibraryEvents, 121 ePropertyDetachKeepsStopped 122 }; 123 124 ProcessProperties::ProcessProperties (bool is_global) : 125 Properties () 126 { 127 if (is_global) 128 { 129 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process"))); 130 m_collection_sp->Initialize(g_properties); 131 m_collection_sp->AppendProperty(ConstString("thread"), 132 ConstString("Settings specific to threads."), 133 true, 134 Thread::GetGlobalProperties()->GetValueProperties()); 135 } 136 else 137 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get())); 138 } 139 140 ProcessProperties::~ProcessProperties() 141 { 142 } 143 144 bool 145 ProcessProperties::GetDisableMemoryCache() const 146 { 147 const uint32_t idx = ePropertyDisableMemCache; 148 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0); 149 } 150 151 Args 152 ProcessProperties::GetExtraStartupCommands () const 153 { 154 Args args; 155 const uint32_t idx = ePropertyExtraStartCommand; 156 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args); 157 return args; 158 } 159 160 void 161 ProcessProperties::SetExtraStartupCommands (const Args &args) 162 { 163 const uint32_t idx = ePropertyExtraStartCommand; 164 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args); 165 } 166 167 FileSpec 168 ProcessProperties::GetPythonOSPluginPath () const 169 { 170 const uint32_t idx = ePropertyPythonOSPluginPath; 171 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx); 172 } 173 174 void 175 ProcessProperties::SetPythonOSPluginPath (const FileSpec &file) 176 { 177 const uint32_t idx = ePropertyPythonOSPluginPath; 178 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file); 179 } 180 181 182 bool 183 ProcessProperties::GetIgnoreBreakpointsInExpressions () const 184 { 185 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions; 186 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0); 187 } 188 189 void 190 ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore) 191 { 192 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions; 193 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore); 194 } 195 196 bool 197 ProcessProperties::GetUnwindOnErrorInExpressions () const 198 { 199 const uint32_t idx = ePropertyUnwindOnErrorInExpressions; 200 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0); 201 } 202 203 void 204 ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore) 205 { 206 const uint32_t idx = ePropertyUnwindOnErrorInExpressions; 207 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore); 208 } 209 210 bool 211 ProcessProperties::GetStopOnSharedLibraryEvents () const 212 { 213 const uint32_t idx = ePropertyStopOnSharedLibraryEvents; 214 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0); 215 } 216 217 void 218 ProcessProperties::SetStopOnSharedLibraryEvents (bool stop) 219 { 220 const uint32_t idx = ePropertyStopOnSharedLibraryEvents; 221 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop); 222 } 223 224 bool 225 ProcessProperties::GetDetachKeepsStopped () const 226 { 227 const uint32_t idx = ePropertyDetachKeepsStopped; 228 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0); 229 } 230 231 void 232 ProcessProperties::SetDetachKeepsStopped (bool stop) 233 { 234 const uint32_t idx = ePropertyDetachKeepsStopped; 235 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop); 236 } 237 238 void 239 ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const 240 { 241 const char *cstr; 242 if (m_pid != LLDB_INVALID_PROCESS_ID) 243 s.Printf (" pid = %" PRIu64 "\n", m_pid); 244 245 if (m_parent_pid != LLDB_INVALID_PROCESS_ID) 246 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid); 247 248 if (m_executable) 249 { 250 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString()); 251 s.PutCString (" file = "); 252 m_executable.Dump(&s); 253 s.EOL(); 254 } 255 const uint32_t argc = m_arguments.GetArgumentCount(); 256 if (argc > 0) 257 { 258 for (uint32_t i=0; i<argc; i++) 259 { 260 const char *arg = m_arguments.GetArgumentAtIndex(i); 261 if (i < 10) 262 s.Printf (" arg[%u] = %s\n", i, arg); 263 else 264 s.Printf ("arg[%u] = %s\n", i, arg); 265 } 266 } 267 268 const uint32_t envc = m_environment.GetArgumentCount(); 269 if (envc > 0) 270 { 271 for (uint32_t i=0; i<envc; i++) 272 { 273 const char *env = m_environment.GetArgumentAtIndex(i); 274 if (i < 10) 275 s.Printf (" env[%u] = %s\n", i, env); 276 else 277 s.Printf ("env[%u] = %s\n", i, env); 278 } 279 } 280 281 if (m_arch.IsValid()) 282 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str()); 283 284 if (m_uid != UINT32_MAX) 285 { 286 cstr = platform->GetUserName (m_uid); 287 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : ""); 288 } 289 if (m_gid != UINT32_MAX) 290 { 291 cstr = platform->GetGroupName (m_gid); 292 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : ""); 293 } 294 if (m_euid != UINT32_MAX) 295 { 296 cstr = platform->GetUserName (m_euid); 297 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : ""); 298 } 299 if (m_egid != UINT32_MAX) 300 { 301 cstr = platform->GetGroupName (m_egid); 302 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : ""); 303 } 304 } 305 306 void 307 ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose) 308 { 309 const char *label; 310 if (show_args || verbose) 311 label = "ARGUMENTS"; 312 else 313 label = "NAME"; 314 315 if (verbose) 316 { 317 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label); 318 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n"); 319 } 320 else 321 { 322 s.Printf ("PID PARENT USER TRIPLE %s\n", label); 323 s.PutCString ("====== ====== ========== ======================== ============================\n"); 324 } 325 } 326 327 void 328 ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const 329 { 330 if (m_pid != LLDB_INVALID_PROCESS_ID) 331 { 332 const char *cstr; 333 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid); 334 335 336 if (verbose) 337 { 338 cstr = platform->GetUserName (m_uid); 339 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed 340 s.Printf ("%-10s ", cstr); 341 else 342 s.Printf ("%-10u ", m_uid); 343 344 cstr = platform->GetGroupName (m_gid); 345 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed 346 s.Printf ("%-10s ", cstr); 347 else 348 s.Printf ("%-10u ", m_gid); 349 350 cstr = platform->GetUserName (m_euid); 351 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed 352 s.Printf ("%-10s ", cstr); 353 else 354 s.Printf ("%-10u ", m_euid); 355 356 cstr = platform->GetGroupName (m_egid); 357 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed 358 s.Printf ("%-10s ", cstr); 359 else 360 s.Printf ("%-10u ", m_egid); 361 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : ""); 362 } 363 else 364 { 365 s.Printf ("%-10s %-24s ", 366 platform->GetUserName (m_euid), 367 m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : ""); 368 } 369 370 if (verbose || show_args) 371 { 372 const uint32_t argc = m_arguments.GetArgumentCount(); 373 if (argc > 0) 374 { 375 for (uint32_t i=0; i<argc; i++) 376 { 377 if (i > 0) 378 s.PutChar (' '); 379 s.PutCString (m_arguments.GetArgumentAtIndex(i)); 380 } 381 } 382 } 383 else 384 { 385 s.PutCString (GetName()); 386 } 387 388 s.EOL(); 389 } 390 } 391 392 Error 393 ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg) 394 { 395 Error error; 396 const int short_option = m_getopt_table[option_idx].val; 397 398 switch (short_option) 399 { 400 case 's': // Stop at program entry point 401 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry); 402 break; 403 404 case 'i': // STDIN for read only 405 { 406 FileAction action; 407 if (action.Open (STDIN_FILENO, option_arg, true, false)) 408 launch_info.AppendFileAction (action); 409 break; 410 } 411 412 case 'o': // Open STDOUT for write only 413 { 414 FileAction action; 415 if (action.Open (STDOUT_FILENO, option_arg, false, true)) 416 launch_info.AppendFileAction (action); 417 break; 418 } 419 420 case 'e': // STDERR for write only 421 { 422 FileAction action; 423 if (action.Open (STDERR_FILENO, option_arg, false, true)) 424 launch_info.AppendFileAction (action); 425 break; 426 } 427 428 case 'p': // Process plug-in name 429 launch_info.SetProcessPluginName (option_arg); 430 break; 431 432 case 'n': // Disable STDIO 433 { 434 FileAction action; 435 if (action.Open (STDIN_FILENO, "/dev/null", true, false)) 436 launch_info.AppendFileAction (action); 437 if (action.Open (STDOUT_FILENO, "/dev/null", false, true)) 438 launch_info.AppendFileAction (action); 439 if (action.Open (STDERR_FILENO, "/dev/null", false, true)) 440 launch_info.AppendFileAction (action); 441 break; 442 } 443 444 case 'w': 445 launch_info.SetWorkingDirectory (option_arg); 446 break; 447 448 case 't': // Open process in new terminal window 449 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY); 450 break; 451 452 case 'a': 453 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get())) 454 launch_info.GetArchitecture().SetTriple (option_arg); 455 break; 456 457 case 'A': // Disable ASLR. 458 { 459 bool success; 460 const bool disable_aslr_arg = Args::StringToBoolean (option_arg, true, &success); 461 if (success) 462 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo; 463 else 464 error.SetErrorStringWithFormat ("Invalid boolean value for disable-aslr option: '%s'", option_arg ? option_arg : "<null>"); 465 break; 466 } 467 468 case 'c': 469 if (option_arg && option_arg[0]) 470 launch_info.SetShell (option_arg); 471 else 472 launch_info.SetShell (LLDB_DEFAULT_SHELL); 473 break; 474 475 case 'v': 476 launch_info.GetEnvironmentEntries().AppendArgument(option_arg); 477 break; 478 479 default: 480 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option); 481 break; 482 } 483 return error; 484 } 485 486 OptionDefinition 487 ProcessLaunchCommandOptions::g_option_table[] = 488 { 489 { LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."}, 490 { LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeBoolean, "Set whether to disable address space layout randomization when launching a process."}, 491 { LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."}, 492 { LLDB_OPT_SET_ALL, false, "working-dir", 'w', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."}, 493 { LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."}, 494 { LLDB_OPT_SET_ALL, false, "environment", 'v', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeNone, "Specify an environment variable name/value string (--environment NAME=VALUE). Can be specified multiple times for subsequent environment entries."}, 495 { LLDB_OPT_SET_ALL, false, "shell", 'c', OptionParser::eOptionalArgument, NULL, NULL, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."}, 496 497 { LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."}, 498 { LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."}, 499 { LLDB_OPT_SET_1 , false, "stderr", 'e', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>."}, 500 501 { LLDB_OPT_SET_2 , false, "tty", 't', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."}, 502 503 { LLDB_OPT_SET_3 , false, "no-stdio", 'n', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."}, 504 505 { 0 , false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL } 506 }; 507 508 509 510 bool 511 ProcessInstanceInfoMatch::NameMatches (const char *process_name) const 512 { 513 if (m_name_match_type == eNameMatchIgnore || process_name == NULL) 514 return true; 515 const char *match_name = m_match_info.GetName(); 516 if (!match_name) 517 return true; 518 519 return lldb_private::NameMatches (process_name, m_name_match_type, match_name); 520 } 521 522 bool 523 ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const 524 { 525 if (!NameMatches (proc_info.GetName())) 526 return false; 527 528 if (m_match_info.ProcessIDIsValid() && 529 m_match_info.GetProcessID() != proc_info.GetProcessID()) 530 return false; 531 532 if (m_match_info.ParentProcessIDIsValid() && 533 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID()) 534 return false; 535 536 if (m_match_info.UserIDIsValid () && 537 m_match_info.GetUserID() != proc_info.GetUserID()) 538 return false; 539 540 if (m_match_info.GroupIDIsValid () && 541 m_match_info.GetGroupID() != proc_info.GetGroupID()) 542 return false; 543 544 if (m_match_info.EffectiveUserIDIsValid () && 545 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID()) 546 return false; 547 548 if (m_match_info.EffectiveGroupIDIsValid () && 549 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID()) 550 return false; 551 552 if (m_match_info.GetArchitecture().IsValid() && 553 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture())) 554 return false; 555 return true; 556 } 557 558 bool 559 ProcessInstanceInfoMatch::MatchAllProcesses () const 560 { 561 if (m_name_match_type != eNameMatchIgnore) 562 return false; 563 564 if (m_match_info.ProcessIDIsValid()) 565 return false; 566 567 if (m_match_info.ParentProcessIDIsValid()) 568 return false; 569 570 if (m_match_info.UserIDIsValid ()) 571 return false; 572 573 if (m_match_info.GroupIDIsValid ()) 574 return false; 575 576 if (m_match_info.EffectiveUserIDIsValid ()) 577 return false; 578 579 if (m_match_info.EffectiveGroupIDIsValid ()) 580 return false; 581 582 if (m_match_info.GetArchitecture().IsValid()) 583 return false; 584 585 if (m_match_all_users) 586 return false; 587 588 return true; 589 590 } 591 592 void 593 ProcessInstanceInfoMatch::Clear() 594 { 595 m_match_info.Clear(); 596 m_name_match_type = eNameMatchIgnore; 597 m_match_all_users = false; 598 } 599 600 ProcessSP 601 Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path) 602 { 603 static uint32_t g_process_unique_id = 0; 604 605 ProcessSP process_sp; 606 ProcessCreateInstance create_callback = NULL; 607 if (plugin_name) 608 { 609 ConstString const_plugin_name(plugin_name); 610 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name); 611 if (create_callback) 612 { 613 process_sp = create_callback(target, listener, crash_file_path); 614 if (process_sp) 615 { 616 if (process_sp->CanDebug(target, true)) 617 { 618 process_sp->m_process_unique_id = ++g_process_unique_id; 619 } 620 else 621 process_sp.reset(); 622 } 623 } 624 } 625 else 626 { 627 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx) 628 { 629 process_sp = create_callback(target, listener, crash_file_path); 630 if (process_sp) 631 { 632 if (process_sp->CanDebug(target, false)) 633 { 634 process_sp->m_process_unique_id = ++g_process_unique_id; 635 break; 636 } 637 else 638 process_sp.reset(); 639 } 640 } 641 } 642 return process_sp; 643 } 644 645 ConstString & 646 Process::GetStaticBroadcasterClass () 647 { 648 static ConstString class_name ("lldb.process"); 649 return class_name; 650 } 651 652 //---------------------------------------------------------------------- 653 // Process constructor 654 //---------------------------------------------------------------------- 655 Process::Process(Target &target, Listener &listener) : 656 ProcessProperties (false), 657 UserID (LLDB_INVALID_PROCESS_ID), 658 Broadcaster (&(target.GetDebugger()), "lldb.process"), 659 m_target (target), 660 m_public_state (eStateUnloaded), 661 m_private_state (eStateUnloaded), 662 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"), 663 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"), 664 m_private_state_listener ("lldb.process.internal_state_listener"), 665 m_private_state_control_wait(), 666 m_private_state_thread (LLDB_INVALID_HOST_THREAD), 667 m_mod_id (), 668 m_process_unique_id(0), 669 m_thread_index_id (0), 670 m_thread_id_to_index_id_map (), 671 m_exit_status (-1), 672 m_exit_string (), 673 m_thread_mutex (Mutex::eMutexTypeRecursive), 674 m_thread_list_real (this), 675 m_thread_list (this), 676 m_extended_thread_list (this), 677 m_extended_thread_stop_id (0), 678 m_queue_list (this), 679 m_queue_list_stop_id (0), 680 m_notifications (), 681 m_image_tokens (), 682 m_listener (listener), 683 m_breakpoint_site_list (), 684 m_dynamic_checkers_ap (), 685 m_unix_signals (), 686 m_abi_sp (), 687 m_process_input_reader (), 688 m_stdio_communication ("process.stdio"), 689 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive), 690 m_stdout_data (), 691 m_stderr_data (), 692 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive), 693 m_profile_data (), 694 m_iohandler_sync (false), 695 m_memory_cache (*this), 696 m_allocated_memory_cache (*this), 697 m_should_detach (false), 698 m_next_event_action_ap(), 699 m_public_run_lock (), 700 m_private_run_lock (), 701 m_currently_handling_event(false), 702 m_finalize_called(false), 703 m_clear_thread_plans_on_stop (false), 704 m_force_next_event_delivery(false), 705 m_last_broadcast_state (eStateInvalid), 706 m_destroy_in_process (false), 707 m_can_jit(eCanJITDontKnow) 708 { 709 CheckInWithManager (); 710 711 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); 712 if (log) 713 log->Printf ("%p Process::Process()", static_cast<void*>(this)); 714 715 SetEventName (eBroadcastBitStateChanged, "state-changed"); 716 SetEventName (eBroadcastBitInterrupt, "interrupt"); 717 SetEventName (eBroadcastBitSTDOUT, "stdout-available"); 718 SetEventName (eBroadcastBitSTDERR, "stderr-available"); 719 SetEventName (eBroadcastBitProfileData, "profile-data-available"); 720 721 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" ); 722 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" ); 723 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume"); 724 725 listener.StartListeningForEvents (this, 726 eBroadcastBitStateChanged | 727 eBroadcastBitInterrupt | 728 eBroadcastBitSTDOUT | 729 eBroadcastBitSTDERR | 730 eBroadcastBitProfileData); 731 732 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster, 733 eBroadcastBitStateChanged | 734 eBroadcastBitInterrupt); 735 736 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster, 737 eBroadcastInternalStateControlStop | 738 eBroadcastInternalStateControlPause | 739 eBroadcastInternalStateControlResume); 740 } 741 742 //---------------------------------------------------------------------- 743 // Destructor 744 //---------------------------------------------------------------------- 745 Process::~Process() 746 { 747 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); 748 if (log) 749 log->Printf ("%p Process::~Process()", static_cast<void*>(this)); 750 StopPrivateStateThread(); 751 } 752 753 const ProcessPropertiesSP & 754 Process::GetGlobalProperties() 755 { 756 static ProcessPropertiesSP g_settings_sp; 757 if (!g_settings_sp) 758 g_settings_sp.reset (new ProcessProperties (true)); 759 return g_settings_sp; 760 } 761 762 void 763 Process::Finalize() 764 { 765 switch (GetPrivateState()) 766 { 767 case eStateConnected: 768 case eStateAttaching: 769 case eStateLaunching: 770 case eStateStopped: 771 case eStateRunning: 772 case eStateStepping: 773 case eStateCrashed: 774 case eStateSuspended: 775 if (GetShouldDetach()) 776 { 777 // FIXME: This will have to be a process setting: 778 bool keep_stopped = false; 779 Detach(keep_stopped); 780 } 781 else 782 Destroy(); 783 break; 784 785 case eStateInvalid: 786 case eStateUnloaded: 787 case eStateDetached: 788 case eStateExited: 789 break; 790 } 791 792 // Clear our broadcaster before we proceed with destroying 793 Broadcaster::Clear(); 794 795 // Do any cleanup needed prior to being destructed... Subclasses 796 // that override this method should call this superclass method as well. 797 798 // We need to destroy the loader before the derived Process class gets destroyed 799 // since it is very likely that undoing the loader will require access to the real process. 800 m_dynamic_checkers_ap.reset(); 801 m_abi_sp.reset(); 802 m_os_ap.reset(); 803 m_system_runtime_ap.reset(); 804 m_dyld_ap.reset(); 805 m_jit_loaders_ap.reset(); 806 m_thread_list_real.Destroy(); 807 m_thread_list.Destroy(); 808 m_extended_thread_list.Destroy(); 809 m_queue_list.Clear(); 810 m_queue_list_stop_id = 0; 811 std::vector<Notifications> empty_notifications; 812 m_notifications.swap(empty_notifications); 813 m_image_tokens.clear(); 814 m_memory_cache.Clear(); 815 m_allocated_memory_cache.Clear(); 816 m_language_runtimes.clear(); 817 m_next_event_action_ap.reset(); 818 //#ifdef LLDB_CONFIGURATION_DEBUG 819 // StreamFile s(stdout, false); 820 // EventSP event_sp; 821 // while (m_private_state_listener.GetNextEvent(event_sp)) 822 // { 823 // event_sp->Dump (&s); 824 // s.EOL(); 825 // } 826 //#endif 827 // We have to be very careful here as the m_private_state_listener might 828 // contain events that have ProcessSP values in them which can keep this 829 // process around forever. These events need to be cleared out. 830 m_private_state_listener.Clear(); 831 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked 832 m_public_run_lock.SetStopped(); 833 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked 834 m_private_run_lock.SetStopped(); 835 m_finalize_called = true; 836 } 837 838 void 839 Process::RegisterNotificationCallbacks (const Notifications& callbacks) 840 { 841 m_notifications.push_back(callbacks); 842 if (callbacks.initialize != NULL) 843 callbacks.initialize (callbacks.baton, this); 844 } 845 846 bool 847 Process::UnregisterNotificationCallbacks(const Notifications& callbacks) 848 { 849 std::vector<Notifications>::iterator pos, end = m_notifications.end(); 850 for (pos = m_notifications.begin(); pos != end; ++pos) 851 { 852 if (pos->baton == callbacks.baton && 853 pos->initialize == callbacks.initialize && 854 pos->process_state_changed == callbacks.process_state_changed) 855 { 856 m_notifications.erase(pos); 857 return true; 858 } 859 } 860 return false; 861 } 862 863 void 864 Process::SynchronouslyNotifyStateChanged (StateType state) 865 { 866 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end(); 867 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos) 868 { 869 if (notification_pos->process_state_changed) 870 notification_pos->process_state_changed (notification_pos->baton, this, state); 871 } 872 } 873 874 // FIXME: We need to do some work on events before the general Listener sees them. 875 // For instance if we are continuing from a breakpoint, we need to ensure that we do 876 // the little "insert real insn, step & stop" trick. But we can't do that when the 877 // event is delivered by the broadcaster - since that is done on the thread that is 878 // waiting for new events, so if we needed more than one event for our handling, we would 879 // stall. So instead we do it when we fetch the event off of the queue. 880 // 881 882 StateType 883 Process::GetNextEvent (EventSP &event_sp) 884 { 885 StateType state = eStateInvalid; 886 887 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp) 888 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get()); 889 890 return state; 891 } 892 893 bool 894 Process::SyncIOHandler (uint64_t timeout_msec) 895 { 896 bool timed_out = false; 897 898 // don't sync (potentially context switch) in case where there is no process IO 899 if (m_process_input_reader) 900 { 901 TimeValue timeout = TimeValue::Now(); 902 timeout.OffsetWithMicroSeconds(timeout_msec*1000); 903 904 m_iohandler_sync.WaitForValueEqualTo(true, &timeout, &timed_out); 905 906 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 907 if(log) 908 { 909 if(timed_out) 910 log->Printf ("Process::%s pid %" PRIu64 " (timeout=%" PRIu64 "ms): FAIL", __FUNCTION__, GetID (), timeout_msec); 911 else 912 log->Printf ("Process::%s pid %" PRIu64 ": SUCCESS", __FUNCTION__, GetID ()); 913 } 914 915 // reset sync one-shot so it will be ready for next time 916 m_iohandler_sync.SetValue(false, eBroadcastNever); 917 } 918 919 return !timed_out; 920 } 921 922 StateType 923 Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr, bool wait_always, Listener *hijack_listener) 924 { 925 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target. 926 // We have to actually check each event, and in the case of a stopped event check the restarted flag 927 // on the event. 928 if (event_sp_ptr) 929 event_sp_ptr->reset(); 930 StateType state = GetState(); 931 // If we are exited or detached, we won't ever get back to any 932 // other valid state... 933 if (state == eStateDetached || state == eStateExited) 934 return state; 935 936 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 937 if (log) 938 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__, 939 static_cast<const void*>(timeout)); 940 941 if (!wait_always && 942 StateIsStoppedState(state, true) && 943 StateIsStoppedState(GetPrivateState(), true)) { 944 if (log) 945 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.", 946 __FUNCTION__); 947 return state; 948 } 949 950 while (state != eStateInvalid) 951 { 952 EventSP event_sp; 953 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener); 954 if (event_sp_ptr && event_sp) 955 *event_sp_ptr = event_sp; 956 957 switch (state) 958 { 959 case eStateCrashed: 960 case eStateDetached: 961 case eStateExited: 962 case eStateUnloaded: 963 // We need to toggle the run lock as this won't get done in 964 // SetPublicState() if the process is hijacked. 965 if (hijack_listener) 966 m_public_run_lock.SetStopped(); 967 return state; 968 case eStateStopped: 969 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) 970 continue; 971 else 972 { 973 // We need to toggle the run lock as this won't get done in 974 // SetPublicState() if the process is hijacked. 975 if (hijack_listener) 976 m_public_run_lock.SetStopped(); 977 return state; 978 } 979 default: 980 continue; 981 } 982 } 983 return state; 984 } 985 986 987 StateType 988 Process::WaitForState 989 ( 990 const TimeValue *timeout, 991 const StateType *match_states, 992 const uint32_t num_match_states 993 ) 994 { 995 EventSP event_sp; 996 uint32_t i; 997 StateType state = GetState(); 998 while (state != eStateInvalid) 999 { 1000 // If we are exited or detached, we won't ever get back to any 1001 // other valid state... 1002 if (state == eStateDetached || state == eStateExited) 1003 return state; 1004 1005 state = WaitForStateChangedEvents (timeout, event_sp, NULL); 1006 1007 for (i=0; i<num_match_states; ++i) 1008 { 1009 if (match_states[i] == state) 1010 return state; 1011 } 1012 } 1013 return state; 1014 } 1015 1016 bool 1017 Process::HijackProcessEvents (Listener *listener) 1018 { 1019 if (listener != NULL) 1020 { 1021 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt); 1022 } 1023 else 1024 return false; 1025 } 1026 1027 void 1028 Process::RestoreProcessEvents () 1029 { 1030 RestoreBroadcaster(); 1031 } 1032 1033 bool 1034 Process::HijackPrivateProcessEvents (Listener *listener) 1035 { 1036 if (listener != NULL) 1037 { 1038 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt); 1039 } 1040 else 1041 return false; 1042 } 1043 1044 void 1045 Process::RestorePrivateProcessEvents () 1046 { 1047 m_private_state_broadcaster.RestoreBroadcaster(); 1048 } 1049 1050 StateType 1051 Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener) 1052 { 1053 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1054 1055 if (log) 1056 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, 1057 static_cast<const void*>(timeout)); 1058 1059 Listener *listener = hijack_listener; 1060 if (listener == NULL) 1061 listener = &m_listener; 1062 1063 StateType state = eStateInvalid; 1064 if (listener->WaitForEventForBroadcasterWithType (timeout, 1065 this, 1066 eBroadcastBitStateChanged | eBroadcastBitInterrupt, 1067 event_sp)) 1068 { 1069 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged) 1070 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 1071 else if (log) 1072 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__); 1073 } 1074 1075 if (log) 1076 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", 1077 __FUNCTION__, static_cast<const void*>(timeout), 1078 StateAsCString(state)); 1079 return state; 1080 } 1081 1082 Event * 1083 Process::PeekAtStateChangedEvents () 1084 { 1085 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1086 1087 if (log) 1088 log->Printf ("Process::%s...", __FUNCTION__); 1089 1090 Event *event_ptr; 1091 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this, 1092 eBroadcastBitStateChanged); 1093 if (log) 1094 { 1095 if (event_ptr) 1096 { 1097 log->Printf ("Process::%s (event_ptr) => %s", 1098 __FUNCTION__, 1099 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr))); 1100 } 1101 else 1102 { 1103 log->Printf ("Process::%s no events found", 1104 __FUNCTION__); 1105 } 1106 } 1107 return event_ptr; 1108 } 1109 1110 StateType 1111 Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp) 1112 { 1113 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1114 1115 if (log) 1116 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, 1117 static_cast<const void*>(timeout)); 1118 1119 StateType state = eStateInvalid; 1120 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout, 1121 &m_private_state_broadcaster, 1122 eBroadcastBitStateChanged | eBroadcastBitInterrupt, 1123 event_sp)) 1124 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged) 1125 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 1126 1127 // This is a bit of a hack, but when we wait here we could very well return 1128 // to the command-line, and that could disable the log, which would render the 1129 // log we got above invalid. 1130 if (log) 1131 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", 1132 __FUNCTION__, static_cast<const void *>(timeout), 1133 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state)); 1134 return state; 1135 } 1136 1137 bool 1138 Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only) 1139 { 1140 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1141 1142 if (log) 1143 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, 1144 static_cast<const void*>(timeout)); 1145 1146 if (control_only) 1147 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp); 1148 else 1149 return m_private_state_listener.WaitForEvent(timeout, event_sp); 1150 } 1151 1152 bool 1153 Process::IsRunning () const 1154 { 1155 return StateIsRunningState (m_public_state.GetValue()); 1156 } 1157 1158 int 1159 Process::GetExitStatus () 1160 { 1161 if (m_public_state.GetValue() == eStateExited) 1162 return m_exit_status; 1163 return -1; 1164 } 1165 1166 1167 const char * 1168 Process::GetExitDescription () 1169 { 1170 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty()) 1171 return m_exit_string.c_str(); 1172 return NULL; 1173 } 1174 1175 bool 1176 Process::SetExitStatus (int status, const char *cstr) 1177 { 1178 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); 1179 if (log) 1180 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)", 1181 status, status, 1182 cstr ? "\"" : "", 1183 cstr ? cstr : "NULL", 1184 cstr ? "\"" : ""); 1185 1186 // We were already in the exited state 1187 if (m_private_state.GetValue() == eStateExited) 1188 { 1189 if (log) 1190 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited"); 1191 return false; 1192 } 1193 1194 m_exit_status = status; 1195 if (cstr) 1196 m_exit_string = cstr; 1197 else 1198 m_exit_string.clear(); 1199 1200 DidExit (); 1201 1202 SetPrivateState (eStateExited); 1203 return true; 1204 } 1205 1206 // This static callback can be used to watch for local child processes on 1207 // the current host. The child process exits, the process will be 1208 // found in the global target list (we want to be completely sure that the 1209 // lldb_private::Process doesn't go away before we can deliver the signal. 1210 bool 1211 Process::SetProcessExitStatus (void *callback_baton, 1212 lldb::pid_t pid, 1213 bool exited, 1214 int signo, // Zero for no signal 1215 int exit_status // Exit value of process if signal is zero 1216 ) 1217 { 1218 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS)); 1219 if (log) 1220 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n", 1221 callback_baton, 1222 pid, 1223 exited, 1224 signo, 1225 exit_status); 1226 1227 if (exited) 1228 { 1229 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid)); 1230 if (target_sp) 1231 { 1232 ProcessSP process_sp (target_sp->GetProcessSP()); 1233 if (process_sp) 1234 { 1235 const char *signal_cstr = NULL; 1236 if (signo) 1237 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo); 1238 1239 process_sp->SetExitStatus (exit_status, signal_cstr); 1240 } 1241 } 1242 return true; 1243 } 1244 return false; 1245 } 1246 1247 1248 void 1249 Process::UpdateThreadListIfNeeded () 1250 { 1251 const uint32_t stop_id = GetStopID(); 1252 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID()) 1253 { 1254 const StateType state = GetPrivateState(); 1255 if (StateIsStoppedState (state, true)) 1256 { 1257 Mutex::Locker locker (m_thread_list.GetMutex ()); 1258 // m_thread_list does have its own mutex, but we need to 1259 // hold onto the mutex between the call to UpdateThreadList(...) 1260 // and the os->UpdateThreadList(...) so it doesn't change on us 1261 ThreadList &old_thread_list = m_thread_list; 1262 ThreadList real_thread_list(this); 1263 ThreadList new_thread_list(this); 1264 // Always update the thread list with the protocol specific 1265 // thread list, but only update if "true" is returned 1266 if (UpdateThreadList (m_thread_list_real, real_thread_list)) 1267 { 1268 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since 1269 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is 1270 // shutting us down, causing a deadlock. 1271 if (!m_destroy_in_process) 1272 { 1273 OperatingSystem *os = GetOperatingSystem (); 1274 if (os) 1275 { 1276 // Clear any old backing threads where memory threads might have been 1277 // backed by actual threads from the lldb_private::Process subclass 1278 size_t num_old_threads = old_thread_list.GetSize(false); 1279 for (size_t i=0; i<num_old_threads; ++i) 1280 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread(); 1281 1282 // Now let the OperatingSystem plug-in update the thread list 1283 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in 1284 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass 1285 new_thread_list); // The new thread list that we will show to the user that gets filled in 1286 } 1287 else 1288 { 1289 // No OS plug-in, the new thread list is the same as the real thread list 1290 new_thread_list = real_thread_list; 1291 } 1292 } 1293 1294 m_thread_list_real.Update(real_thread_list); 1295 m_thread_list.Update (new_thread_list); 1296 m_thread_list.SetStopID (stop_id); 1297 1298 if (GetLastNaturalStopID () != m_extended_thread_stop_id) 1299 { 1300 // Clear any extended threads that we may have accumulated previously 1301 m_extended_thread_list.Clear(); 1302 m_extended_thread_stop_id = GetLastNaturalStopID (); 1303 1304 m_queue_list.Clear(); 1305 m_queue_list_stop_id = GetLastNaturalStopID (); 1306 } 1307 } 1308 } 1309 } 1310 } 1311 1312 void 1313 Process::UpdateQueueListIfNeeded () 1314 { 1315 if (m_system_runtime_ap.get()) 1316 { 1317 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID()) 1318 { 1319 const StateType state = GetPrivateState(); 1320 if (StateIsStoppedState (state, true)) 1321 { 1322 m_system_runtime_ap->PopulateQueueList (m_queue_list); 1323 m_queue_list_stop_id = GetLastNaturalStopID(); 1324 } 1325 } 1326 } 1327 } 1328 1329 ThreadSP 1330 Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context) 1331 { 1332 OperatingSystem *os = GetOperatingSystem (); 1333 if (os) 1334 return os->CreateThread(tid, context); 1335 return ThreadSP(); 1336 } 1337 1338 uint32_t 1339 Process::GetNextThreadIndexID (uint64_t thread_id) 1340 { 1341 return AssignIndexIDToThread(thread_id); 1342 } 1343 1344 bool 1345 Process::HasAssignedIndexIDToThread(uint64_t thread_id) 1346 { 1347 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id); 1348 if (iterator == m_thread_id_to_index_id_map.end()) 1349 { 1350 return false; 1351 } 1352 else 1353 { 1354 return true; 1355 } 1356 } 1357 1358 uint32_t 1359 Process::AssignIndexIDToThread(uint64_t thread_id) 1360 { 1361 uint32_t result = 0; 1362 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id); 1363 if (iterator == m_thread_id_to_index_id_map.end()) 1364 { 1365 result = ++m_thread_index_id; 1366 m_thread_id_to_index_id_map[thread_id] = result; 1367 } 1368 else 1369 { 1370 result = iterator->second; 1371 } 1372 1373 return result; 1374 } 1375 1376 StateType 1377 Process::GetState() 1378 { 1379 // If any other threads access this we will need a mutex for it 1380 return m_public_state.GetValue (); 1381 } 1382 1383 void 1384 Process::SetPublicState (StateType new_state, bool restarted) 1385 { 1386 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); 1387 if (log) 1388 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted); 1389 const StateType old_state = m_public_state.GetValue(); 1390 m_public_state.SetValue (new_state); 1391 1392 // On the transition from Run to Stopped, we unlock the writer end of the 1393 // run lock. The lock gets locked in Resume, which is the public API 1394 // to tell the program to run. 1395 if (!IsHijackedForEvent(eBroadcastBitStateChanged)) 1396 { 1397 if (new_state == eStateDetached) 1398 { 1399 if (log) 1400 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state)); 1401 m_public_run_lock.SetStopped(); 1402 } 1403 else 1404 { 1405 const bool old_state_is_stopped = StateIsStoppedState(old_state, false); 1406 const bool new_state_is_stopped = StateIsStoppedState(new_state, false); 1407 if ((old_state_is_stopped != new_state_is_stopped)) 1408 { 1409 if (new_state_is_stopped && !restarted) 1410 { 1411 if (log) 1412 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state)); 1413 m_public_run_lock.SetStopped(); 1414 } 1415 } 1416 } 1417 } 1418 } 1419 1420 Error 1421 Process::Resume () 1422 { 1423 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); 1424 if (log) 1425 log->Printf("Process::Resume -- locking run lock"); 1426 if (!m_public_run_lock.TrySetRunning()) 1427 { 1428 Error error("Resume request failed - process still running."); 1429 if (log) 1430 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming."); 1431 return error; 1432 } 1433 return PrivateResume(); 1434 } 1435 1436 StateType 1437 Process::GetPrivateState () 1438 { 1439 return m_private_state.GetValue(); 1440 } 1441 1442 void 1443 Process::SetPrivateState (StateType new_state) 1444 { 1445 if (m_finalize_called) 1446 return; 1447 1448 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); 1449 bool state_changed = false; 1450 1451 if (log) 1452 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state)); 1453 1454 Mutex::Locker thread_locker(m_thread_list.GetMutex()); 1455 Mutex::Locker locker(m_private_state.GetMutex()); 1456 1457 const StateType old_state = m_private_state.GetValueNoLock (); 1458 state_changed = old_state != new_state; 1459 1460 const bool old_state_is_stopped = StateIsStoppedState(old_state, false); 1461 const bool new_state_is_stopped = StateIsStoppedState(new_state, false); 1462 if (old_state_is_stopped != new_state_is_stopped) 1463 { 1464 if (new_state_is_stopped) 1465 m_private_run_lock.SetStopped(); 1466 else 1467 m_private_run_lock.SetRunning(); 1468 } 1469 1470 if (state_changed) 1471 { 1472 m_private_state.SetValueNoLock (new_state); 1473 if (StateIsStoppedState(new_state, false)) 1474 { 1475 // Note, this currently assumes that all threads in the list 1476 // stop when the process stops. In the future we will want to 1477 // support a debugging model where some threads continue to run 1478 // while others are stopped. When that happens we will either need 1479 // a way for the thread list to identify which threads are stopping 1480 // or create a special thread list containing only threads which 1481 // actually stopped. 1482 // 1483 // The process plugin is responsible for managing the actual 1484 // behavior of the threads and should have stopped any threads 1485 // that are going to stop before we get here. 1486 m_thread_list.DidStop(); 1487 1488 m_mod_id.BumpStopID(); 1489 m_memory_cache.Clear(); 1490 if (log) 1491 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID()); 1492 } 1493 // Use our target to get a shared pointer to ourselves... 1494 if (m_finalize_called && PrivateStateThreadIsValid() == false) 1495 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state)); 1496 else 1497 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state)); 1498 } 1499 else 1500 { 1501 if (log) 1502 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state)); 1503 } 1504 } 1505 1506 void 1507 Process::SetRunningUserExpression (bool on) 1508 { 1509 m_mod_id.SetRunningUserExpression (on); 1510 } 1511 1512 addr_t 1513 Process::GetImageInfoAddress() 1514 { 1515 return LLDB_INVALID_ADDRESS; 1516 } 1517 1518 //---------------------------------------------------------------------- 1519 // LoadImage 1520 // 1521 // This function provides a default implementation that works for most 1522 // unix variants. Any Process subclasses that need to do shared library 1523 // loading differently should override LoadImage and UnloadImage and 1524 // do what is needed. 1525 //---------------------------------------------------------------------- 1526 uint32_t 1527 Process::LoadImage (const FileSpec &image_spec, Error &error) 1528 { 1529 char path[PATH_MAX]; 1530 image_spec.GetPath(path, sizeof(path)); 1531 1532 DynamicLoader *loader = GetDynamicLoader(); 1533 if (loader) 1534 { 1535 error = loader->CanLoadImage(); 1536 if (error.Fail()) 1537 return LLDB_INVALID_IMAGE_TOKEN; 1538 } 1539 1540 if (error.Success()) 1541 { 1542 ThreadSP thread_sp(GetThreadList ().GetSelectedThread()); 1543 1544 if (thread_sp) 1545 { 1546 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0)); 1547 1548 if (frame_sp) 1549 { 1550 ExecutionContext exe_ctx; 1551 frame_sp->CalculateExecutionContext (exe_ctx); 1552 EvaluateExpressionOptions expr_options; 1553 expr_options.SetUnwindOnError(true); 1554 expr_options.SetIgnoreBreakpoints(true); 1555 expr_options.SetExecutionPolicy(eExecutionPolicyAlways); 1556 expr_options.SetResultIsInternal(true); 1557 1558 StreamString expr; 1559 expr.Printf(R"( 1560 struct __lldb_dlopen_result { void *image_ptr; const char *error_str; } the_result; 1561 the_result.image_ptr = dlopen ("%s", 2); 1562 if (the_result.image_ptr == (void *) 0x0) 1563 { 1564 the_result.error_str = dlerror(); 1565 } 1566 else 1567 { 1568 the_result.error_str = (const char *) 0x0; 1569 } 1570 the_result; 1571 )", 1572 path); 1573 const char *prefix = R"( 1574 extern "C" void* dlopen (const char *path, int mode); 1575 extern "C" const char *dlerror (void); 1576 )"; 1577 lldb::ValueObjectSP result_valobj_sp; 1578 Error expr_error; 1579 ClangUserExpression::Evaluate (exe_ctx, 1580 expr_options, 1581 expr.GetData(), 1582 prefix, 1583 result_valobj_sp, 1584 expr_error); 1585 if (expr_error.Success()) 1586 { 1587 error = result_valobj_sp->GetError(); 1588 if (error.Success()) 1589 { 1590 Scalar scalar; 1591 ValueObjectSP image_ptr_sp = result_valobj_sp->GetChildAtIndex(0, true); 1592 if (image_ptr_sp && image_ptr_sp->ResolveValue (scalar)) 1593 { 1594 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS); 1595 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS) 1596 { 1597 uint32_t image_token = m_image_tokens.size(); 1598 m_image_tokens.push_back (image_ptr); 1599 return image_token; 1600 } 1601 else if (image_ptr == 0) 1602 { 1603 ValueObjectSP error_str_sp = result_valobj_sp->GetChildAtIndex(1, true); 1604 if (error_str_sp) 1605 { 1606 if (error_str_sp->IsCStringContainer(true)) 1607 { 1608 StreamString s; 1609 size_t num_chars = error_str_sp->ReadPointedString (s, error); 1610 if (error.Success() && num_chars > 0) 1611 { 1612 error.Clear(); 1613 error.SetErrorStringWithFormat("dlopen error: %s", s.GetData()); 1614 } 1615 } 1616 } 1617 } 1618 } 1619 } 1620 } 1621 else 1622 error = expr_error; 1623 } 1624 } 1625 } 1626 if (!error.AsCString()) 1627 error.SetErrorStringWithFormat("unable to load '%s'", path); 1628 return LLDB_INVALID_IMAGE_TOKEN; 1629 } 1630 1631 //---------------------------------------------------------------------- 1632 // UnloadImage 1633 // 1634 // This function provides a default implementation that works for most 1635 // unix variants. Any Process subclasses that need to do shared library 1636 // loading differently should override LoadImage and UnloadImage and 1637 // do what is needed. 1638 //---------------------------------------------------------------------- 1639 Error 1640 Process::UnloadImage (uint32_t image_token) 1641 { 1642 Error error; 1643 if (image_token < m_image_tokens.size()) 1644 { 1645 const addr_t image_addr = m_image_tokens[image_token]; 1646 if (image_addr == LLDB_INVALID_ADDRESS) 1647 { 1648 error.SetErrorString("image already unloaded"); 1649 } 1650 else 1651 { 1652 DynamicLoader *loader = GetDynamicLoader(); 1653 if (loader) 1654 error = loader->CanLoadImage(); 1655 1656 if (error.Success()) 1657 { 1658 ThreadSP thread_sp(GetThreadList ().GetSelectedThread()); 1659 1660 if (thread_sp) 1661 { 1662 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0)); 1663 1664 if (frame_sp) 1665 { 1666 ExecutionContext exe_ctx; 1667 frame_sp->CalculateExecutionContext (exe_ctx); 1668 EvaluateExpressionOptions expr_options; 1669 expr_options.SetUnwindOnError(true); 1670 expr_options.SetIgnoreBreakpoints(true); 1671 expr_options.SetExecutionPolicy(eExecutionPolicyAlways); 1672 StreamString expr; 1673 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr); 1674 const char *prefix = "extern \"C\" int dlclose(void* handle);\n"; 1675 lldb::ValueObjectSP result_valobj_sp; 1676 Error expr_error; 1677 ClangUserExpression::Evaluate (exe_ctx, 1678 expr_options, 1679 expr.GetData(), 1680 prefix, 1681 result_valobj_sp, 1682 expr_error); 1683 if (result_valobj_sp->GetError().Success()) 1684 { 1685 Scalar scalar; 1686 if (result_valobj_sp->ResolveValue (scalar)) 1687 { 1688 if (scalar.UInt(1)) 1689 { 1690 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData()); 1691 } 1692 else 1693 { 1694 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS; 1695 } 1696 } 1697 } 1698 else 1699 { 1700 error = result_valobj_sp->GetError(); 1701 } 1702 } 1703 } 1704 } 1705 } 1706 } 1707 else 1708 { 1709 error.SetErrorString("invalid image token"); 1710 } 1711 return error; 1712 } 1713 1714 const lldb::ABISP & 1715 Process::GetABI() 1716 { 1717 if (!m_abi_sp) 1718 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture()); 1719 return m_abi_sp; 1720 } 1721 1722 LanguageRuntime * 1723 Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null) 1724 { 1725 LanguageRuntimeCollection::iterator pos; 1726 pos = m_language_runtimes.find (language); 1727 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second)) 1728 { 1729 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language)); 1730 1731 m_language_runtimes[language] = runtime_sp; 1732 return runtime_sp.get(); 1733 } 1734 else 1735 return (*pos).second.get(); 1736 } 1737 1738 CPPLanguageRuntime * 1739 Process::GetCPPLanguageRuntime (bool retry_if_null) 1740 { 1741 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null); 1742 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus) 1743 return static_cast<CPPLanguageRuntime *> (runtime); 1744 return NULL; 1745 } 1746 1747 ObjCLanguageRuntime * 1748 Process::GetObjCLanguageRuntime (bool retry_if_null) 1749 { 1750 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null); 1751 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC) 1752 return static_cast<ObjCLanguageRuntime *> (runtime); 1753 return NULL; 1754 } 1755 1756 bool 1757 Process::IsPossibleDynamicValue (ValueObject& in_value) 1758 { 1759 if (in_value.IsDynamic()) 1760 return false; 1761 LanguageType known_type = in_value.GetObjectRuntimeLanguage(); 1762 1763 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) 1764 { 1765 LanguageRuntime *runtime = GetLanguageRuntime (known_type); 1766 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false; 1767 } 1768 1769 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus); 1770 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value)) 1771 return true; 1772 1773 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC); 1774 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false; 1775 } 1776 1777 BreakpointSiteList & 1778 Process::GetBreakpointSiteList() 1779 { 1780 return m_breakpoint_site_list; 1781 } 1782 1783 const BreakpointSiteList & 1784 Process::GetBreakpointSiteList() const 1785 { 1786 return m_breakpoint_site_list; 1787 } 1788 1789 1790 void 1791 Process::DisableAllBreakpointSites () 1792 { 1793 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void { 1794 // bp_site->SetEnabled(true); 1795 DisableBreakpointSite(bp_site); 1796 }); 1797 } 1798 1799 Error 1800 Process::ClearBreakpointSiteByID (lldb::user_id_t break_id) 1801 { 1802 Error error (DisableBreakpointSiteByID (break_id)); 1803 1804 if (error.Success()) 1805 m_breakpoint_site_list.Remove(break_id); 1806 1807 return error; 1808 } 1809 1810 Error 1811 Process::DisableBreakpointSiteByID (lldb::user_id_t break_id) 1812 { 1813 Error error; 1814 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id); 1815 if (bp_site_sp) 1816 { 1817 if (bp_site_sp->IsEnabled()) 1818 error = DisableBreakpointSite (bp_site_sp.get()); 1819 } 1820 else 1821 { 1822 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id); 1823 } 1824 1825 return error; 1826 } 1827 1828 Error 1829 Process::EnableBreakpointSiteByID (lldb::user_id_t break_id) 1830 { 1831 Error error; 1832 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id); 1833 if (bp_site_sp) 1834 { 1835 if (!bp_site_sp->IsEnabled()) 1836 error = EnableBreakpointSite (bp_site_sp.get()); 1837 } 1838 else 1839 { 1840 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id); 1841 } 1842 return error; 1843 } 1844 1845 lldb::break_id_t 1846 Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware) 1847 { 1848 addr_t load_addr = LLDB_INVALID_ADDRESS; 1849 1850 bool show_error = true; 1851 switch (GetState()) 1852 { 1853 case eStateInvalid: 1854 case eStateUnloaded: 1855 case eStateConnected: 1856 case eStateAttaching: 1857 case eStateLaunching: 1858 case eStateDetached: 1859 case eStateExited: 1860 show_error = false; 1861 break; 1862 1863 case eStateStopped: 1864 case eStateRunning: 1865 case eStateStepping: 1866 case eStateCrashed: 1867 case eStateSuspended: 1868 show_error = IsAlive(); 1869 break; 1870 } 1871 1872 // Reset the IsIndirect flag here, in case the location changes from 1873 // pointing to a indirect symbol to a regular symbol. 1874 owner->SetIsIndirect (false); 1875 1876 if (owner->ShouldResolveIndirectFunctions()) 1877 { 1878 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol(); 1879 if (symbol && symbol->IsIndirect()) 1880 { 1881 Error error; 1882 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error); 1883 if (!error.Success() && show_error) 1884 { 1885 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n", 1886 symbol->GetAddress().GetLoadAddress(&m_target), 1887 owner->GetBreakpoint().GetID(), 1888 owner->GetID(), 1889 error.AsCString() ? error.AsCString() : "unknown error"); 1890 return LLDB_INVALID_BREAK_ID; 1891 } 1892 Address resolved_address(load_addr); 1893 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target); 1894 owner->SetIsIndirect(true); 1895 } 1896 else 1897 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target); 1898 } 1899 else 1900 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target); 1901 1902 if (load_addr != LLDB_INVALID_ADDRESS) 1903 { 1904 BreakpointSiteSP bp_site_sp; 1905 1906 // Look up this breakpoint site. If it exists, then add this new owner, otherwise 1907 // create a new breakpoint site and add it. 1908 1909 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr); 1910 1911 if (bp_site_sp) 1912 { 1913 bp_site_sp->AddOwner (owner); 1914 owner->SetBreakpointSite (bp_site_sp); 1915 return bp_site_sp->GetID(); 1916 } 1917 else 1918 { 1919 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware)); 1920 if (bp_site_sp) 1921 { 1922 Error error = EnableBreakpointSite (bp_site_sp.get()); 1923 if (error.Success()) 1924 { 1925 owner->SetBreakpointSite (bp_site_sp); 1926 return m_breakpoint_site_list.Add (bp_site_sp); 1927 } 1928 else 1929 { 1930 if (show_error) 1931 { 1932 // Report error for setting breakpoint... 1933 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n", 1934 load_addr, 1935 owner->GetBreakpoint().GetID(), 1936 owner->GetID(), 1937 error.AsCString() ? error.AsCString() : "unknown error"); 1938 } 1939 } 1940 } 1941 } 1942 } 1943 // We failed to enable the breakpoint 1944 return LLDB_INVALID_BREAK_ID; 1945 1946 } 1947 1948 void 1949 Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp) 1950 { 1951 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id); 1952 if (num_owners == 0) 1953 { 1954 // Don't try to disable the site if we don't have a live process anymore. 1955 if (IsAlive()) 1956 DisableBreakpointSite (bp_site_sp.get()); 1957 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress()); 1958 } 1959 } 1960 1961 1962 size_t 1963 Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const 1964 { 1965 size_t bytes_removed = 0; 1966 BreakpointSiteList bp_sites_in_range; 1967 1968 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range)) 1969 { 1970 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void { 1971 if (bp_site->GetType() == BreakpointSite::eSoftware) 1972 { 1973 addr_t intersect_addr; 1974 size_t intersect_size; 1975 size_t opcode_offset; 1976 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset)) 1977 { 1978 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size); 1979 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size); 1980 assert(opcode_offset + intersect_size <= bp_site->GetByteSize()); 1981 size_t buf_offset = intersect_addr - bp_addr; 1982 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size); 1983 } 1984 } 1985 }); 1986 } 1987 return bytes_removed; 1988 } 1989 1990 1991 1992 size_t 1993 Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site) 1994 { 1995 PlatformSP platform_sp (m_target.GetPlatform()); 1996 if (platform_sp) 1997 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site); 1998 return 0; 1999 } 2000 2001 Error 2002 Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site) 2003 { 2004 Error error; 2005 assert (bp_site != NULL); 2006 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 2007 const addr_t bp_addr = bp_site->GetLoadAddress(); 2008 if (log) 2009 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr); 2010 if (bp_site->IsEnabled()) 2011 { 2012 if (log) 2013 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already enabled", bp_site->GetID(), (uint64_t)bp_addr); 2014 return error; 2015 } 2016 2017 if (bp_addr == LLDB_INVALID_ADDRESS) 2018 { 2019 error.SetErrorString("BreakpointSite contains an invalid load address."); 2020 return error; 2021 } 2022 // Ask the lldb::Process subclass to fill in the correct software breakpoint 2023 // trap for the breakpoint site 2024 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site); 2025 2026 if (bp_opcode_size == 0) 2027 { 2028 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr); 2029 } 2030 else 2031 { 2032 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes(); 2033 2034 if (bp_opcode_bytes == NULL) 2035 { 2036 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode."); 2037 return error; 2038 } 2039 2040 // Save the original opcode by reading it 2041 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size) 2042 { 2043 // Write a software breakpoint in place of the original opcode 2044 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size) 2045 { 2046 uint8_t verify_bp_opcode_bytes[64]; 2047 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size) 2048 { 2049 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0) 2050 { 2051 bp_site->SetEnabled(true); 2052 bp_site->SetType (BreakpointSite::eSoftware); 2053 if (log) 2054 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS", 2055 bp_site->GetID(), 2056 (uint64_t)bp_addr); 2057 } 2058 else 2059 error.SetErrorString("failed to verify the breakpoint trap in memory."); 2060 } 2061 else 2062 error.SetErrorString("Unable to read memory to verify breakpoint trap."); 2063 } 2064 else 2065 error.SetErrorString("Unable to write breakpoint trap to memory."); 2066 } 2067 else 2068 error.SetErrorString("Unable to read memory at breakpoint address."); 2069 } 2070 if (log && error.Fail()) 2071 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s", 2072 bp_site->GetID(), 2073 (uint64_t)bp_addr, 2074 error.AsCString()); 2075 return error; 2076 } 2077 2078 Error 2079 Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site) 2080 { 2081 Error error; 2082 assert (bp_site != NULL); 2083 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 2084 addr_t bp_addr = bp_site->GetLoadAddress(); 2085 lldb::user_id_t breakID = bp_site->GetID(); 2086 if (log) 2087 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr); 2088 2089 if (bp_site->IsHardware()) 2090 { 2091 error.SetErrorString("Breakpoint site is a hardware breakpoint."); 2092 } 2093 else if (bp_site->IsEnabled()) 2094 { 2095 const size_t break_op_size = bp_site->GetByteSize(); 2096 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes(); 2097 if (break_op_size > 0) 2098 { 2099 // Clear a software breakpoint instruction 2100 uint8_t curr_break_op[8]; 2101 assert (break_op_size <= sizeof(curr_break_op)); 2102 bool break_op_found = false; 2103 2104 // Read the breakpoint opcode 2105 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size) 2106 { 2107 bool verify = false; 2108 // Make sure we have the a breakpoint opcode exists at this address 2109 if (::memcmp (curr_break_op, break_op, break_op_size) == 0) 2110 { 2111 break_op_found = true; 2112 // We found a valid breakpoint opcode at this address, now restore 2113 // the saved opcode. 2114 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size) 2115 { 2116 verify = true; 2117 } 2118 else 2119 error.SetErrorString("Memory write failed when restoring original opcode."); 2120 } 2121 else 2122 { 2123 error.SetErrorString("Original breakpoint trap is no longer in memory."); 2124 // Set verify to true and so we can check if the original opcode has already been restored 2125 verify = true; 2126 } 2127 2128 if (verify) 2129 { 2130 uint8_t verify_opcode[8]; 2131 assert (break_op_size < sizeof(verify_opcode)); 2132 // Verify that our original opcode made it back to the inferior 2133 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size) 2134 { 2135 // compare the memory we just read with the original opcode 2136 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0) 2137 { 2138 // SUCCESS 2139 bp_site->SetEnabled(false); 2140 if (log) 2141 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr); 2142 return error; 2143 } 2144 else 2145 { 2146 if (break_op_found) 2147 error.SetErrorString("Failed to restore original opcode."); 2148 } 2149 } 2150 else 2151 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored."); 2152 } 2153 } 2154 else 2155 error.SetErrorString("Unable to read memory that should contain the breakpoint trap."); 2156 } 2157 } 2158 else 2159 { 2160 if (log) 2161 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already disabled", bp_site->GetID(), (uint64_t)bp_addr); 2162 return error; 2163 } 2164 2165 if (log) 2166 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s", 2167 bp_site->GetID(), 2168 (uint64_t)bp_addr, 2169 error.AsCString()); 2170 return error; 2171 2172 } 2173 2174 // Uncomment to verify memory caching works after making changes to caching code 2175 //#define VERIFY_MEMORY_READS 2176 2177 size_t 2178 Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error) 2179 { 2180 error.Clear(); 2181 if (!GetDisableMemoryCache()) 2182 { 2183 #if defined (VERIFY_MEMORY_READS) 2184 // Memory caching is enabled, with debug verification 2185 2186 if (buf && size) 2187 { 2188 // Uncomment the line below to make sure memory caching is working. 2189 // I ran this through the test suite and got no assertions, so I am 2190 // pretty confident this is working well. If any changes are made to 2191 // memory caching, uncomment the line below and test your changes! 2192 2193 // Verify all memory reads by using the cache first, then redundantly 2194 // reading the same memory from the inferior and comparing to make sure 2195 // everything is exactly the same. 2196 std::string verify_buf (size, '\0'); 2197 assert (verify_buf.size() == size); 2198 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error); 2199 Error verify_error; 2200 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error); 2201 assert (cache_bytes_read == verify_bytes_read); 2202 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0); 2203 assert (verify_error.Success() == error.Success()); 2204 return cache_bytes_read; 2205 } 2206 return 0; 2207 #else // !defined(VERIFY_MEMORY_READS) 2208 // Memory caching is enabled, without debug verification 2209 2210 return m_memory_cache.Read (addr, buf, size, error); 2211 #endif // defined (VERIFY_MEMORY_READS) 2212 } 2213 else 2214 { 2215 // Memory caching is disabled 2216 2217 return ReadMemoryFromInferior (addr, buf, size, error); 2218 } 2219 } 2220 2221 size_t 2222 Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error) 2223 { 2224 char buf[256]; 2225 out_str.clear(); 2226 addr_t curr_addr = addr; 2227 while (1) 2228 { 2229 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error); 2230 if (length == 0) 2231 break; 2232 out_str.append(buf, length); 2233 // If we got "length - 1" bytes, we didn't get the whole C string, we 2234 // need to read some more characters 2235 if (length == sizeof(buf) - 1) 2236 curr_addr += length; 2237 else 2238 break; 2239 } 2240 return out_str.size(); 2241 } 2242 2243 2244 size_t 2245 Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error, 2246 size_t type_width) 2247 { 2248 size_t total_bytes_read = 0; 2249 if (dst && max_bytes && type_width && max_bytes >= type_width) 2250 { 2251 // Ensure a null terminator independent of the number of bytes that is read. 2252 memset (dst, 0, max_bytes); 2253 size_t bytes_left = max_bytes - type_width; 2254 2255 const char terminator[4] = {'\0', '\0', '\0', '\0'}; 2256 assert(sizeof(terminator) >= type_width && 2257 "Attempting to validate a string with more than 4 bytes per character!"); 2258 2259 addr_t curr_addr = addr; 2260 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize(); 2261 char *curr_dst = dst; 2262 2263 error.Clear(); 2264 while (bytes_left > 0 && error.Success()) 2265 { 2266 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size); 2267 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left); 2268 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error); 2269 2270 if (bytes_read == 0) 2271 break; 2272 2273 // Search for a null terminator of correct size and alignment in bytes_read 2274 size_t aligned_start = total_bytes_read - total_bytes_read % type_width; 2275 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width) 2276 if (::strncmp(&dst[i], terminator, type_width) == 0) 2277 { 2278 error.Clear(); 2279 return i; 2280 } 2281 2282 total_bytes_read += bytes_read; 2283 curr_dst += bytes_read; 2284 curr_addr += bytes_read; 2285 bytes_left -= bytes_read; 2286 } 2287 } 2288 else 2289 { 2290 if (max_bytes) 2291 error.SetErrorString("invalid arguments"); 2292 } 2293 return total_bytes_read; 2294 } 2295 2296 // Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find 2297 // null terminators. 2298 size_t 2299 Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error) 2300 { 2301 size_t total_cstr_len = 0; 2302 if (dst && dst_max_len) 2303 { 2304 result_error.Clear(); 2305 // NULL out everything just to be safe 2306 memset (dst, 0, dst_max_len); 2307 Error error; 2308 addr_t curr_addr = addr; 2309 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize(); 2310 size_t bytes_left = dst_max_len - 1; 2311 char *curr_dst = dst; 2312 2313 while (bytes_left > 0) 2314 { 2315 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size); 2316 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left); 2317 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error); 2318 2319 if (bytes_read == 0) 2320 { 2321 result_error = error; 2322 dst[total_cstr_len] = '\0'; 2323 break; 2324 } 2325 const size_t len = strlen(curr_dst); 2326 2327 total_cstr_len += len; 2328 2329 if (len < bytes_to_read) 2330 break; 2331 2332 curr_dst += bytes_read; 2333 curr_addr += bytes_read; 2334 bytes_left -= bytes_read; 2335 } 2336 } 2337 else 2338 { 2339 if (dst == NULL) 2340 result_error.SetErrorString("invalid arguments"); 2341 else 2342 result_error.Clear(); 2343 } 2344 return total_cstr_len; 2345 } 2346 2347 size_t 2348 Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error) 2349 { 2350 if (buf == NULL || size == 0) 2351 return 0; 2352 2353 size_t bytes_read = 0; 2354 uint8_t *bytes = (uint8_t *)buf; 2355 2356 while (bytes_read < size) 2357 { 2358 const size_t curr_size = size - bytes_read; 2359 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read, 2360 bytes + bytes_read, 2361 curr_size, 2362 error); 2363 bytes_read += curr_bytes_read; 2364 if (curr_bytes_read == curr_size || curr_bytes_read == 0) 2365 break; 2366 } 2367 2368 // Replace any software breakpoint opcodes that fall into this range back 2369 // into "buf" before we return 2370 if (bytes_read > 0) 2371 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf); 2372 return bytes_read; 2373 } 2374 2375 uint64_t 2376 Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error) 2377 { 2378 Scalar scalar; 2379 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error)) 2380 return scalar.ULongLong(fail_value); 2381 return fail_value; 2382 } 2383 2384 addr_t 2385 Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error) 2386 { 2387 Scalar scalar; 2388 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error)) 2389 return scalar.ULongLong(LLDB_INVALID_ADDRESS); 2390 return LLDB_INVALID_ADDRESS; 2391 } 2392 2393 2394 bool 2395 Process::WritePointerToMemory (lldb::addr_t vm_addr, 2396 lldb::addr_t ptr_value, 2397 Error &error) 2398 { 2399 Scalar scalar; 2400 const uint32_t addr_byte_size = GetAddressByteSize(); 2401 if (addr_byte_size <= 4) 2402 scalar = (uint32_t)ptr_value; 2403 else 2404 scalar = ptr_value; 2405 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size; 2406 } 2407 2408 size_t 2409 Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error) 2410 { 2411 size_t bytes_written = 0; 2412 const uint8_t *bytes = (const uint8_t *)buf; 2413 2414 while (bytes_written < size) 2415 { 2416 const size_t curr_size = size - bytes_written; 2417 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written, 2418 bytes + bytes_written, 2419 curr_size, 2420 error); 2421 bytes_written += curr_bytes_written; 2422 if (curr_bytes_written == curr_size || curr_bytes_written == 0) 2423 break; 2424 } 2425 return bytes_written; 2426 } 2427 2428 size_t 2429 Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error) 2430 { 2431 #if defined (ENABLE_MEMORY_CACHING) 2432 m_memory_cache.Flush (addr, size); 2433 #endif 2434 2435 if (buf == NULL || size == 0) 2436 return 0; 2437 2438 m_mod_id.BumpMemoryID(); 2439 2440 // We need to write any data that would go where any current software traps 2441 // (enabled software breakpoints) any software traps (breakpoints) that we 2442 // may have placed in our tasks memory. 2443 2444 BreakpointSiteList bp_sites_in_range; 2445 2446 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range)) 2447 { 2448 // No breakpoint sites overlap 2449 if (bp_sites_in_range.IsEmpty()) 2450 return WriteMemoryPrivate (addr, buf, size, error); 2451 else 2452 { 2453 const uint8_t *ubuf = (const uint8_t *)buf; 2454 uint64_t bytes_written = 0; 2455 2456 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void { 2457 2458 if (error.Success()) 2459 { 2460 addr_t intersect_addr; 2461 size_t intersect_size; 2462 size_t opcode_offset; 2463 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset); 2464 assert(intersects); 2465 assert(addr <= intersect_addr && intersect_addr < addr + size); 2466 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size); 2467 assert(opcode_offset + intersect_size <= bp->GetByteSize()); 2468 2469 // Check for bytes before this breakpoint 2470 const addr_t curr_addr = addr + bytes_written; 2471 if (intersect_addr > curr_addr) 2472 { 2473 // There are some bytes before this breakpoint that we need to 2474 // just write to memory 2475 size_t curr_size = intersect_addr - curr_addr; 2476 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr, 2477 ubuf + bytes_written, 2478 curr_size, 2479 error); 2480 bytes_written += curr_bytes_written; 2481 if (curr_bytes_written != curr_size) 2482 { 2483 // We weren't able to write all of the requested bytes, we 2484 // are done looping and will return the number of bytes that 2485 // we have written so far. 2486 if (error.Success()) 2487 error.SetErrorToGenericError(); 2488 } 2489 } 2490 // Now write any bytes that would cover up any software breakpoints 2491 // directly into the breakpoint opcode buffer 2492 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size); 2493 bytes_written += intersect_size; 2494 } 2495 }); 2496 2497 if (bytes_written < size) 2498 bytes_written += WriteMemoryPrivate (addr + bytes_written, 2499 ubuf + bytes_written, 2500 size - bytes_written, 2501 error); 2502 } 2503 } 2504 else 2505 { 2506 return WriteMemoryPrivate (addr, buf, size, error); 2507 } 2508 2509 // Write any remaining bytes after the last breakpoint if we have any left 2510 return 0; //bytes_written; 2511 } 2512 2513 size_t 2514 Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error) 2515 { 2516 if (byte_size == UINT32_MAX) 2517 byte_size = scalar.GetByteSize(); 2518 if (byte_size > 0) 2519 { 2520 uint8_t buf[32]; 2521 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error); 2522 if (mem_size > 0) 2523 return WriteMemory(addr, buf, mem_size, error); 2524 else 2525 error.SetErrorString ("failed to get scalar as memory data"); 2526 } 2527 else 2528 { 2529 error.SetErrorString ("invalid scalar value"); 2530 } 2531 return 0; 2532 } 2533 2534 size_t 2535 Process::ReadScalarIntegerFromMemory (addr_t addr, 2536 uint32_t byte_size, 2537 bool is_signed, 2538 Scalar &scalar, 2539 Error &error) 2540 { 2541 uint64_t uval = 0; 2542 if (byte_size == 0) 2543 { 2544 error.SetErrorString ("byte size is zero"); 2545 } 2546 else if (byte_size & (byte_size - 1)) 2547 { 2548 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size); 2549 } 2550 else if (byte_size <= sizeof(uval)) 2551 { 2552 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error); 2553 if (bytes_read == byte_size) 2554 { 2555 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize()); 2556 lldb::offset_t offset = 0; 2557 if (byte_size <= 4) 2558 scalar = data.GetMaxU32 (&offset, byte_size); 2559 else 2560 scalar = data.GetMaxU64 (&offset, byte_size); 2561 if (is_signed) 2562 scalar.SignExtend(byte_size * 8); 2563 return bytes_read; 2564 } 2565 } 2566 else 2567 { 2568 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size); 2569 } 2570 return 0; 2571 } 2572 2573 #define USE_ALLOCATE_MEMORY_CACHE 1 2574 addr_t 2575 Process::AllocateMemory(size_t size, uint32_t permissions, Error &error) 2576 { 2577 if (GetPrivateState() != eStateStopped) 2578 return LLDB_INVALID_ADDRESS; 2579 2580 #if defined (USE_ALLOCATE_MEMORY_CACHE) 2581 return m_allocated_memory_cache.AllocateMemory(size, permissions, error); 2582 #else 2583 addr_t allocated_addr = DoAllocateMemory (size, permissions, error); 2584 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2585 if (log) 2586 log->Printf("Process::AllocateMemory(size=%" PRIu64 ", permissions=%s) => 0x%16.16" PRIx64 " (m_stop_id = %u m_memory_id = %u)", 2587 (uint64_t)size, 2588 GetPermissionsAsCString (permissions), 2589 (uint64_t)allocated_addr, 2590 m_mod_id.GetStopID(), 2591 m_mod_id.GetMemoryID()); 2592 return allocated_addr; 2593 #endif 2594 } 2595 2596 bool 2597 Process::CanJIT () 2598 { 2599 if (m_can_jit == eCanJITDontKnow) 2600 { 2601 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2602 Error err; 2603 2604 uint64_t allocated_memory = AllocateMemory(8, 2605 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable, 2606 err); 2607 2608 if (err.Success()) 2609 { 2610 m_can_jit = eCanJITYes; 2611 if (log) 2612 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ()); 2613 } 2614 else 2615 { 2616 m_can_jit = eCanJITNo; 2617 if (log) 2618 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ()); 2619 } 2620 2621 DeallocateMemory (allocated_memory); 2622 } 2623 2624 return m_can_jit == eCanJITYes; 2625 } 2626 2627 void 2628 Process::SetCanJIT (bool can_jit) 2629 { 2630 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo); 2631 } 2632 2633 Error 2634 Process::DeallocateMemory (addr_t ptr) 2635 { 2636 Error error; 2637 #if defined (USE_ALLOCATE_MEMORY_CACHE) 2638 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) 2639 { 2640 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr); 2641 } 2642 #else 2643 error = DoDeallocateMemory (ptr); 2644 2645 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2646 if (log) 2647 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64 ") => err = %s (m_stop_id = %u, m_memory_id = %u)", 2648 ptr, 2649 error.AsCString("SUCCESS"), 2650 m_mod_id.GetStopID(), 2651 m_mod_id.GetMemoryID()); 2652 #endif 2653 return error; 2654 } 2655 2656 2657 ModuleSP 2658 Process::ReadModuleFromMemory (const FileSpec& file_spec, 2659 lldb::addr_t header_addr, 2660 size_t size_to_read) 2661 { 2662 ModuleSP module_sp (new Module (file_spec, ArchSpec())); 2663 if (module_sp) 2664 { 2665 Error error; 2666 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read); 2667 if (objfile) 2668 return module_sp; 2669 } 2670 return ModuleSP(); 2671 } 2672 2673 Error 2674 Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify) 2675 { 2676 Error error; 2677 error.SetErrorString("watchpoints are not supported"); 2678 return error; 2679 } 2680 2681 Error 2682 Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify) 2683 { 2684 Error error; 2685 error.SetErrorString("watchpoints are not supported"); 2686 return error; 2687 } 2688 2689 StateType 2690 Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp) 2691 { 2692 StateType state; 2693 // Now wait for the process to launch and return control to us, and then 2694 // call DidLaunch: 2695 while (1) 2696 { 2697 event_sp.reset(); 2698 state = WaitForStateChangedEventsPrivate (timeout, event_sp); 2699 2700 if (StateIsStoppedState(state, false)) 2701 break; 2702 2703 // If state is invalid, then we timed out 2704 if (state == eStateInvalid) 2705 break; 2706 2707 if (event_sp) 2708 HandlePrivateEvent (event_sp); 2709 } 2710 return state; 2711 } 2712 2713 Error 2714 Process::Launch (ProcessLaunchInfo &launch_info) 2715 { 2716 Error error; 2717 m_abi_sp.reset(); 2718 m_dyld_ap.reset(); 2719 m_jit_loaders_ap.reset(); 2720 m_system_runtime_ap.reset(); 2721 m_os_ap.reset(); 2722 m_process_input_reader.reset(); 2723 2724 Module *exe_module = m_target.GetExecutableModulePointer(); 2725 if (exe_module) 2726 { 2727 char local_exec_file_path[PATH_MAX]; 2728 char platform_exec_file_path[PATH_MAX]; 2729 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path)); 2730 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path)); 2731 if (exe_module->GetFileSpec().Exists()) 2732 { 2733 // Install anything that might need to be installed prior to launching. 2734 // For host systems, this will do nothing, but if we are connected to a 2735 // remote platform it will install any needed binaries 2736 error = GetTarget().Install(&launch_info); 2737 if (error.Fail()) 2738 return error; 2739 2740 if (PrivateStateThreadIsValid ()) 2741 PausePrivateStateThread (); 2742 2743 error = WillLaunch (exe_module); 2744 if (error.Success()) 2745 { 2746 const bool restarted = false; 2747 SetPublicState (eStateLaunching, restarted); 2748 m_should_detach = false; 2749 2750 if (m_public_run_lock.TrySetRunning()) 2751 { 2752 // Now launch using these arguments. 2753 error = DoLaunch (exe_module, launch_info); 2754 } 2755 else 2756 { 2757 // This shouldn't happen 2758 error.SetErrorString("failed to acquire process run lock"); 2759 } 2760 2761 if (error.Fail()) 2762 { 2763 if (GetID() != LLDB_INVALID_PROCESS_ID) 2764 { 2765 SetID (LLDB_INVALID_PROCESS_ID); 2766 const char *error_string = error.AsCString(); 2767 if (error_string == NULL) 2768 error_string = "launch failed"; 2769 SetExitStatus (-1, error_string); 2770 } 2771 } 2772 else 2773 { 2774 EventSP event_sp; 2775 TimeValue timeout_time; 2776 timeout_time = TimeValue::Now(); 2777 timeout_time.OffsetWithSeconds(10); 2778 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp); 2779 2780 if (state == eStateInvalid || event_sp.get() == NULL) 2781 { 2782 // We were able to launch the process, but we failed to 2783 // catch the initial stop. 2784 SetExitStatus (0, "failed to catch stop after launch"); 2785 Destroy(); 2786 } 2787 else if (state == eStateStopped || state == eStateCrashed) 2788 { 2789 2790 DidLaunch (); 2791 2792 DynamicLoader *dyld = GetDynamicLoader (); 2793 if (dyld) 2794 dyld->DidLaunch(); 2795 2796 GetJITLoaders().DidLaunch(); 2797 2798 SystemRuntime *system_runtime = GetSystemRuntime (); 2799 if (system_runtime) 2800 system_runtime->DidLaunch(); 2801 2802 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL)); 2803 // This delays passing the stopped event to listeners till DidLaunch gets 2804 // a chance to complete... 2805 HandlePrivateEvent (event_sp); 2806 2807 if (PrivateStateThreadIsValid ()) 2808 ResumePrivateStateThread (); 2809 else 2810 StartPrivateStateThread (); 2811 } 2812 else if (state == eStateExited) 2813 { 2814 // We exited while trying to launch somehow. Don't call DidLaunch as that's 2815 // not likely to work, and return an invalid pid. 2816 HandlePrivateEvent (event_sp); 2817 } 2818 } 2819 } 2820 } 2821 else 2822 { 2823 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path); 2824 } 2825 } 2826 return error; 2827 } 2828 2829 2830 Error 2831 Process::LoadCore () 2832 { 2833 Error error = DoLoadCore(); 2834 if (error.Success()) 2835 { 2836 if (PrivateStateThreadIsValid ()) 2837 ResumePrivateStateThread (); 2838 else 2839 StartPrivateStateThread (); 2840 2841 DynamicLoader *dyld = GetDynamicLoader (); 2842 if (dyld) 2843 dyld->DidAttach(); 2844 2845 GetJITLoaders().DidAttach(); 2846 2847 SystemRuntime *system_runtime = GetSystemRuntime (); 2848 if (system_runtime) 2849 system_runtime->DidAttach(); 2850 2851 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL)); 2852 // We successfully loaded a core file, now pretend we stopped so we can 2853 // show all of the threads in the core file and explore the crashed 2854 // state. 2855 SetPrivateState (eStateStopped); 2856 2857 } 2858 return error; 2859 } 2860 2861 DynamicLoader * 2862 Process::GetDynamicLoader () 2863 { 2864 if (m_dyld_ap.get() == NULL) 2865 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL)); 2866 return m_dyld_ap.get(); 2867 } 2868 2869 const lldb::DataBufferSP 2870 Process::GetAuxvData() 2871 { 2872 return DataBufferSP (); 2873 } 2874 2875 JITLoaderList & 2876 Process::GetJITLoaders () 2877 { 2878 if (!m_jit_loaders_ap) 2879 { 2880 m_jit_loaders_ap.reset(new JITLoaderList()); 2881 JITLoader::LoadPlugins(this, *m_jit_loaders_ap); 2882 } 2883 return *m_jit_loaders_ap; 2884 } 2885 2886 SystemRuntime * 2887 Process::GetSystemRuntime () 2888 { 2889 if (m_system_runtime_ap.get() == NULL) 2890 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this)); 2891 return m_system_runtime_ap.get(); 2892 } 2893 2894 2895 Process::NextEventAction::EventActionResult 2896 Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp) 2897 { 2898 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get()); 2899 switch (state) 2900 { 2901 case eStateRunning: 2902 case eStateConnected: 2903 return eEventActionRetry; 2904 2905 case eStateStopped: 2906 case eStateCrashed: 2907 { 2908 // During attach, prior to sending the eStateStopped event, 2909 // lldb_private::Process subclasses must set the new process ID. 2910 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID); 2911 // We don't want these events to be reported, so go set the ShouldReportStop here: 2912 m_process->GetThreadList().SetShouldReportStop (eVoteNo); 2913 2914 if (m_exec_count > 0) 2915 { 2916 --m_exec_count; 2917 RequestResume(); 2918 return eEventActionRetry; 2919 } 2920 else 2921 { 2922 m_process->CompleteAttach (); 2923 return eEventActionSuccess; 2924 } 2925 } 2926 break; 2927 2928 default: 2929 case eStateExited: 2930 case eStateInvalid: 2931 break; 2932 } 2933 2934 m_exit_string.assign ("No valid Process"); 2935 return eEventActionExit; 2936 } 2937 2938 Process::NextEventAction::EventActionResult 2939 Process::AttachCompletionHandler::HandleBeingInterrupted() 2940 { 2941 return eEventActionSuccess; 2942 } 2943 2944 const char * 2945 Process::AttachCompletionHandler::GetExitString () 2946 { 2947 return m_exit_string.c_str(); 2948 } 2949 2950 Error 2951 Process::Attach (ProcessAttachInfo &attach_info) 2952 { 2953 m_abi_sp.reset(); 2954 m_process_input_reader.reset(); 2955 m_dyld_ap.reset(); 2956 m_jit_loaders_ap.reset(); 2957 m_system_runtime_ap.reset(); 2958 m_os_ap.reset(); 2959 2960 lldb::pid_t attach_pid = attach_info.GetProcessID(); 2961 Error error; 2962 if (attach_pid == LLDB_INVALID_PROCESS_ID) 2963 { 2964 char process_name[PATH_MAX]; 2965 2966 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name))) 2967 { 2968 const bool wait_for_launch = attach_info.GetWaitForLaunch(); 2969 2970 if (wait_for_launch) 2971 { 2972 error = WillAttachToProcessWithName(process_name, wait_for_launch); 2973 if (error.Success()) 2974 { 2975 if (m_public_run_lock.TrySetRunning()) 2976 { 2977 m_should_detach = true; 2978 const bool restarted = false; 2979 SetPublicState (eStateAttaching, restarted); 2980 // Now attach using these arguments. 2981 error = DoAttachToProcessWithName (process_name, attach_info); 2982 } 2983 else 2984 { 2985 // This shouldn't happen 2986 error.SetErrorString("failed to acquire process run lock"); 2987 } 2988 2989 if (error.Fail()) 2990 { 2991 if (GetID() != LLDB_INVALID_PROCESS_ID) 2992 { 2993 SetID (LLDB_INVALID_PROCESS_ID); 2994 if (error.AsCString() == NULL) 2995 error.SetErrorString("attach failed"); 2996 2997 SetExitStatus(-1, error.AsCString()); 2998 } 2999 } 3000 else 3001 { 3002 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount())); 3003 StartPrivateStateThread(); 3004 } 3005 return error; 3006 } 3007 } 3008 else 3009 { 3010 ProcessInstanceInfoList process_infos; 3011 PlatformSP platform_sp (m_target.GetPlatform ()); 3012 3013 if (platform_sp) 3014 { 3015 ProcessInstanceInfoMatch match_info; 3016 match_info.GetProcessInfo() = attach_info; 3017 match_info.SetNameMatchType (eNameMatchEquals); 3018 platform_sp->FindProcesses (match_info, process_infos); 3019 const uint32_t num_matches = process_infos.GetSize(); 3020 if (num_matches == 1) 3021 { 3022 attach_pid = process_infos.GetProcessIDAtIndex(0); 3023 // Fall through and attach using the above process ID 3024 } 3025 else 3026 { 3027 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name)); 3028 if (num_matches > 1) 3029 { 3030 StreamString s; 3031 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false); 3032 for (size_t i = 0; i < num_matches; i++) 3033 { 3034 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false); 3035 } 3036 error.SetErrorStringWithFormat ("more than one process named %s:\n%s", 3037 process_name, 3038 s.GetData()); 3039 } 3040 else 3041 error.SetErrorStringWithFormat ("could not find a process named %s", process_name); 3042 } 3043 } 3044 else 3045 { 3046 error.SetErrorString ("invalid platform, can't find processes by name"); 3047 return error; 3048 } 3049 } 3050 } 3051 else 3052 { 3053 error.SetErrorString ("invalid process name"); 3054 } 3055 } 3056 3057 if (attach_pid != LLDB_INVALID_PROCESS_ID) 3058 { 3059 error = WillAttachToProcessWithID(attach_pid); 3060 if (error.Success()) 3061 { 3062 3063 if (m_public_run_lock.TrySetRunning()) 3064 { 3065 // Now attach using these arguments. 3066 m_should_detach = true; 3067 const bool restarted = false; 3068 SetPublicState (eStateAttaching, restarted); 3069 error = DoAttachToProcessWithID (attach_pid, attach_info); 3070 } 3071 else 3072 { 3073 // This shouldn't happen 3074 error.SetErrorString("failed to acquire process run lock"); 3075 } 3076 3077 if (error.Success()) 3078 { 3079 3080 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount())); 3081 StartPrivateStateThread(); 3082 } 3083 else 3084 { 3085 if (GetID() != LLDB_INVALID_PROCESS_ID) 3086 { 3087 SetID (LLDB_INVALID_PROCESS_ID); 3088 const char *error_string = error.AsCString(); 3089 if (error_string == NULL) 3090 error_string = "attach failed"; 3091 3092 SetExitStatus(-1, error_string); 3093 } 3094 } 3095 } 3096 } 3097 return error; 3098 } 3099 3100 void 3101 Process::CompleteAttach () 3102 { 3103 // Let the process subclass figure out at much as it can about the process 3104 // before we go looking for a dynamic loader plug-in. 3105 ArchSpec process_arch; 3106 DidAttach(process_arch); 3107 3108 if (process_arch.IsValid()) 3109 m_target.SetArchitecture(process_arch); 3110 3111 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't 3112 // the same as the one we've already set, switch architectures. 3113 PlatformSP platform_sp (m_target.GetPlatform ()); 3114 assert (platform_sp.get()); 3115 if (platform_sp) 3116 { 3117 const ArchSpec &target_arch = m_target.GetArchitecture(); 3118 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL)) 3119 { 3120 ArchSpec platform_arch; 3121 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch); 3122 if (platform_sp) 3123 { 3124 m_target.SetPlatform (platform_sp); 3125 m_target.SetArchitecture(platform_arch); 3126 } 3127 } 3128 else if (!process_arch.IsValid()) 3129 { 3130 ProcessInstanceInfo process_info; 3131 platform_sp->GetProcessInfo (GetID(), process_info); 3132 const ArchSpec &process_arch = process_info.GetArchitecture(); 3133 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch)) 3134 m_target.SetArchitecture (process_arch); 3135 } 3136 } 3137 3138 // We have completed the attach, now it is time to find the dynamic loader 3139 // plug-in 3140 DynamicLoader *dyld = GetDynamicLoader (); 3141 if (dyld) 3142 dyld->DidAttach(); 3143 3144 GetJITLoaders().DidAttach(); 3145 3146 SystemRuntime *system_runtime = GetSystemRuntime (); 3147 if (system_runtime) 3148 system_runtime->DidAttach(); 3149 3150 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL)); 3151 // Figure out which one is the executable, and set that in our target: 3152 const ModuleList &target_modules = m_target.GetImages(); 3153 Mutex::Locker modules_locker(target_modules.GetMutex()); 3154 size_t num_modules = target_modules.GetSize(); 3155 ModuleSP new_executable_module_sp; 3156 3157 for (size_t i = 0; i < num_modules; i++) 3158 { 3159 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i)); 3160 if (module_sp && module_sp->IsExecutable()) 3161 { 3162 if (m_target.GetExecutableModulePointer() != module_sp.get()) 3163 new_executable_module_sp = module_sp; 3164 break; 3165 } 3166 } 3167 if (new_executable_module_sp) 3168 m_target.SetExecutableModule (new_executable_module_sp, false); 3169 } 3170 3171 Error 3172 Process::ConnectRemote (Stream *strm, const char *remote_url) 3173 { 3174 m_abi_sp.reset(); 3175 m_process_input_reader.reset(); 3176 3177 // Find the process and its architecture. Make sure it matches the architecture 3178 // of the current Target, and if not adjust it. 3179 3180 Error error (DoConnectRemote (strm, remote_url)); 3181 if (error.Success()) 3182 { 3183 if (GetID() != LLDB_INVALID_PROCESS_ID) 3184 { 3185 EventSP event_sp; 3186 StateType state = WaitForProcessStopPrivate(NULL, event_sp); 3187 3188 if (state == eStateStopped || state == eStateCrashed) 3189 { 3190 // If we attached and actually have a process on the other end, then 3191 // this ended up being the equivalent of an attach. 3192 CompleteAttach (); 3193 3194 // This delays passing the stopped event to listeners till 3195 // CompleteAttach gets a chance to complete... 3196 HandlePrivateEvent (event_sp); 3197 3198 } 3199 } 3200 3201 if (PrivateStateThreadIsValid ()) 3202 ResumePrivateStateThread (); 3203 else 3204 StartPrivateStateThread (); 3205 } 3206 return error; 3207 } 3208 3209 3210 Error 3211 Process::PrivateResume () 3212 { 3213 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP)); 3214 if (log) 3215 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s", 3216 m_mod_id.GetStopID(), 3217 StateAsCString(m_public_state.GetValue()), 3218 StateAsCString(m_private_state.GetValue())); 3219 3220 Error error (WillResume()); 3221 // Tell the process it is about to resume before the thread list 3222 if (error.Success()) 3223 { 3224 // Now let the thread list know we are about to resume so it 3225 // can let all of our threads know that they are about to be 3226 // resumed. Threads will each be called with 3227 // Thread::WillResume(StateType) where StateType contains the state 3228 // that they are supposed to have when the process is resumed 3229 // (suspended/running/stepping). Threads should also check 3230 // their resume signal in lldb::Thread::GetResumeSignal() 3231 // to see if they are supposed to start back up with a signal. 3232 if (m_thread_list.WillResume()) 3233 { 3234 // Last thing, do the PreResumeActions. 3235 if (!RunPreResumeActions()) 3236 { 3237 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming."); 3238 } 3239 else 3240 { 3241 m_mod_id.BumpResumeID(); 3242 error = DoResume(); 3243 if (error.Success()) 3244 { 3245 DidResume(); 3246 m_thread_list.DidResume(); 3247 if (log) 3248 log->Printf ("Process thinks the process has resumed."); 3249 } 3250 } 3251 } 3252 else 3253 { 3254 // Somebody wanted to run without running. So generate a continue & a stopped event, 3255 // and let the world handle them. 3256 if (log) 3257 log->Printf ("Process::PrivateResume() asked to simulate a start & stop."); 3258 3259 SetPrivateState(eStateRunning); 3260 SetPrivateState(eStateStopped); 3261 } 3262 } 3263 else if (log) 3264 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>")); 3265 return error; 3266 } 3267 3268 Error 3269 Process::Halt (bool clear_thread_plans) 3270 { 3271 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if 3272 // in case it was already set and some thread plan logic calls halt on its 3273 // own. 3274 m_clear_thread_plans_on_stop |= clear_thread_plans; 3275 3276 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since 3277 // we could just straightaway get another event. It just narrows the window... 3278 m_currently_handling_event.WaitForValueEqualTo(false); 3279 3280 3281 // Pause our private state thread so we can ensure no one else eats 3282 // the stop event out from under us. 3283 Listener halt_listener ("lldb.process.halt_listener"); 3284 HijackPrivateProcessEvents(&halt_listener); 3285 3286 EventSP event_sp; 3287 Error error (WillHalt()); 3288 3289 bool restored_process_events = false; 3290 if (error.Success()) 3291 { 3292 3293 bool caused_stop = false; 3294 3295 // Ask the process subclass to actually halt our process 3296 error = DoHalt(caused_stop); 3297 if (error.Success()) 3298 { 3299 if (m_public_state.GetValue() == eStateAttaching) 3300 { 3301 // Don't hijack and eat the eStateExited as the code that was doing 3302 // the attach will be waiting for this event... 3303 RestorePrivateProcessEvents(); 3304 restored_process_events = true; 3305 SetExitStatus(SIGKILL, "Cancelled async attach."); 3306 Destroy (); 3307 } 3308 else 3309 { 3310 // If "caused_stop" is true, then DoHalt stopped the process. If 3311 // "caused_stop" is false, the process was already stopped. 3312 // If the DoHalt caused the process to stop, then we want to catch 3313 // this event and set the interrupted bool to true before we pass 3314 // this along so clients know that the process was interrupted by 3315 // a halt command. 3316 if (caused_stop) 3317 { 3318 // Wait for 1 second for the process to stop. 3319 TimeValue timeout_time; 3320 timeout_time = TimeValue::Now(); 3321 timeout_time.OffsetWithSeconds(10); 3322 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp); 3323 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get()); 3324 3325 if (!got_event || state == eStateInvalid) 3326 { 3327 // We timeout out and didn't get a stop event... 3328 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState())); 3329 } 3330 else 3331 { 3332 if (StateIsStoppedState (state, false)) 3333 { 3334 // We caused the process to interrupt itself, so mark this 3335 // as such in the stop event so clients can tell an interrupted 3336 // process from a natural stop 3337 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true); 3338 } 3339 else 3340 { 3341 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3342 if (log) 3343 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state)); 3344 error.SetErrorString ("Did not get stopped event after halt."); 3345 } 3346 } 3347 } 3348 DidHalt(); 3349 } 3350 } 3351 } 3352 // Resume our private state thread before we post the event (if any) 3353 if (!restored_process_events) 3354 RestorePrivateProcessEvents(); 3355 3356 // Post any event we might have consumed. If all goes well, we will have 3357 // stopped the process, intercepted the event and set the interrupted 3358 // bool in the event. Post it to the private event queue and that will end up 3359 // correctly setting the state. 3360 if (event_sp) 3361 m_private_state_broadcaster.BroadcastEvent(event_sp); 3362 3363 return error; 3364 } 3365 3366 Error 3367 Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp) 3368 { 3369 Error error; 3370 if (m_public_state.GetValue() == eStateRunning) 3371 { 3372 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3373 if (log) 3374 log->Printf("Process::Destroy() About to halt."); 3375 error = Halt(); 3376 if (error.Success()) 3377 { 3378 // Consume the halt event. 3379 TimeValue timeout (TimeValue::Now()); 3380 timeout.OffsetWithSeconds(1); 3381 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp); 3382 3383 // If the process exited while we were waiting for it to stop, put the exited event into 3384 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since 3385 // they don't have a process anymore... 3386 3387 if (state == eStateExited || m_private_state.GetValue() == eStateExited) 3388 { 3389 if (log) 3390 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt."); 3391 return error; 3392 } 3393 else 3394 exit_event_sp.reset(); // It is ok to consume any non-exit stop events 3395 3396 if (state != eStateStopped) 3397 { 3398 if (log) 3399 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state)); 3400 // If we really couldn't stop the process then we should just error out here, but if the 3401 // lower levels just bobbled sending the event and we really are stopped, then continue on. 3402 StateType private_state = m_private_state.GetValue(); 3403 if (private_state != eStateStopped) 3404 { 3405 return error; 3406 } 3407 } 3408 } 3409 else 3410 { 3411 if (log) 3412 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString()); 3413 } 3414 } 3415 return error; 3416 } 3417 3418 Error 3419 Process::Detach (bool keep_stopped) 3420 { 3421 EventSP exit_event_sp; 3422 Error error; 3423 m_destroy_in_process = true; 3424 3425 error = WillDetach(); 3426 3427 if (error.Success()) 3428 { 3429 if (DetachRequiresHalt()) 3430 { 3431 error = HaltForDestroyOrDetach (exit_event_sp); 3432 if (!error.Success()) 3433 { 3434 m_destroy_in_process = false; 3435 return error; 3436 } 3437 else if (exit_event_sp) 3438 { 3439 // We shouldn't need to do anything else here. There's no process left to detach from... 3440 StopPrivateStateThread(); 3441 m_destroy_in_process = false; 3442 return error; 3443 } 3444 } 3445 3446 m_thread_list.DiscardThreadPlans(); 3447 DisableAllBreakpointSites(); 3448 3449 error = DoDetach(keep_stopped); 3450 if (error.Success()) 3451 { 3452 DidDetach(); 3453 StopPrivateStateThread(); 3454 } 3455 else 3456 { 3457 return error; 3458 } 3459 } 3460 m_destroy_in_process = false; 3461 3462 // If we exited when we were waiting for a process to stop, then 3463 // forward the event here so we don't lose the event 3464 if (exit_event_sp) 3465 { 3466 // Directly broadcast our exited event because we shut down our 3467 // private state thread above 3468 BroadcastEvent(exit_event_sp); 3469 } 3470 3471 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating 3472 // the last events through the event system, in which case we might strand the write lock. Unlock 3473 // it here so when we do to tear down the process we don't get an error destroying the lock. 3474 3475 m_public_run_lock.SetStopped(); 3476 return error; 3477 } 3478 3479 Error 3480 Process::Destroy () 3481 { 3482 3483 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work 3484 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt 3485 // failed and the process stays around for some reason it won't be in a confused state. 3486 3487 m_destroy_in_process = true; 3488 3489 Error error (WillDestroy()); 3490 if (error.Success()) 3491 { 3492 EventSP exit_event_sp; 3493 if (DestroyRequiresHalt()) 3494 { 3495 error = HaltForDestroyOrDetach(exit_event_sp); 3496 } 3497 3498 if (m_public_state.GetValue() != eStateRunning) 3499 { 3500 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to 3501 // kill it, we don't want it hitting a breakpoint... 3502 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then 3503 // we're not going to have much luck doing this now. 3504 m_thread_list.DiscardThreadPlans(); 3505 DisableAllBreakpointSites(); 3506 } 3507 3508 error = DoDestroy(); 3509 if (error.Success()) 3510 { 3511 DidDestroy(); 3512 StopPrivateStateThread(); 3513 } 3514 m_stdio_communication.StopReadThread(); 3515 m_stdio_communication.Disconnect(); 3516 3517 if (m_process_input_reader) 3518 { 3519 m_process_input_reader->SetIsDone(true); 3520 m_process_input_reader->Cancel(); 3521 m_process_input_reader.reset(); 3522 } 3523 3524 // If we exited when we were waiting for a process to stop, then 3525 // forward the event here so we don't lose the event 3526 if (exit_event_sp) 3527 { 3528 // Directly broadcast our exited event because we shut down our 3529 // private state thread above 3530 BroadcastEvent(exit_event_sp); 3531 } 3532 3533 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating 3534 // the last events through the event system, in which case we might strand the write lock. Unlock 3535 // it here so when we do to tear down the process we don't get an error destroying the lock. 3536 m_public_run_lock.SetStopped(); 3537 } 3538 3539 m_destroy_in_process = false; 3540 3541 return error; 3542 } 3543 3544 Error 3545 Process::Signal (int signal) 3546 { 3547 Error error (WillSignal()); 3548 if (error.Success()) 3549 { 3550 error = DoSignal(signal); 3551 if (error.Success()) 3552 DidSignal(); 3553 } 3554 return error; 3555 } 3556 3557 lldb::ByteOrder 3558 Process::GetByteOrder () const 3559 { 3560 return m_target.GetArchitecture().GetByteOrder(); 3561 } 3562 3563 uint32_t 3564 Process::GetAddressByteSize () const 3565 { 3566 return m_target.GetArchitecture().GetAddressByteSize(); 3567 } 3568 3569 3570 bool 3571 Process::ShouldBroadcastEvent (Event *event_ptr) 3572 { 3573 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr); 3574 bool return_value = true; 3575 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS)); 3576 3577 switch (state) 3578 { 3579 case eStateConnected: 3580 case eStateAttaching: 3581 case eStateLaunching: 3582 case eStateDetached: 3583 case eStateExited: 3584 case eStateUnloaded: 3585 // These events indicate changes in the state of the debugging session, always report them. 3586 return_value = true; 3587 break; 3588 case eStateInvalid: 3589 // We stopped for no apparent reason, don't report it. 3590 return_value = false; 3591 break; 3592 case eStateRunning: 3593 case eStateStepping: 3594 // If we've started the target running, we handle the cases where we 3595 // are already running and where there is a transition from stopped to 3596 // running differently. 3597 // running -> running: Automatically suppress extra running events 3598 // stopped -> running: Report except when there is one or more no votes 3599 // and no yes votes. 3600 SynchronouslyNotifyStateChanged (state); 3601 if (m_force_next_event_delivery) 3602 return_value = true; 3603 else 3604 { 3605 switch (m_last_broadcast_state) 3606 { 3607 case eStateRunning: 3608 case eStateStepping: 3609 // We always suppress multiple runnings with no PUBLIC stop in between. 3610 return_value = false; 3611 break; 3612 default: 3613 // TODO: make this work correctly. For now always report 3614 // run if we aren't running so we don't miss any running 3615 // events. If I run the lldb/test/thread/a.out file and 3616 // break at main.cpp:58, run and hit the breakpoints on 3617 // multiple threads, then somehow during the stepping over 3618 // of all breakpoints no run gets reported. 3619 3620 // This is a transition from stop to run. 3621 switch (m_thread_list.ShouldReportRun (event_ptr)) 3622 { 3623 case eVoteYes: 3624 case eVoteNoOpinion: 3625 return_value = true; 3626 break; 3627 case eVoteNo: 3628 return_value = false; 3629 break; 3630 } 3631 break; 3632 } 3633 } 3634 break; 3635 case eStateStopped: 3636 case eStateCrashed: 3637 case eStateSuspended: 3638 { 3639 // We've stopped. First see if we're going to restart the target. 3640 // If we are going to stop, then we always broadcast the event. 3641 // If we aren't going to stop, let the thread plans decide if we're going to report this event. 3642 // If no thread has an opinion, we don't report it. 3643 3644 RefreshStateAfterStop (); 3645 if (ProcessEventData::GetInterruptedFromEvent (event_ptr)) 3646 { 3647 if (log) 3648 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", 3649 static_cast<void*>(event_ptr), 3650 StateAsCString(state)); 3651 // Even though we know we are going to stop, we should let the threads have a look at the stop, 3652 // so they can properly set their state. 3653 m_thread_list.ShouldStop (event_ptr); 3654 return_value = true; 3655 } 3656 else 3657 { 3658 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr); 3659 bool should_resume = false; 3660 3661 // It makes no sense to ask "ShouldStop" if we've already been restarted... 3662 // Asking the thread list is also not likely to go well, since we are running again. 3663 // So in that case just report the event. 3664 3665 if (!was_restarted) 3666 should_resume = m_thread_list.ShouldStop (event_ptr) == false; 3667 3668 if (was_restarted || should_resume || m_resume_requested) 3669 { 3670 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr); 3671 if (log) 3672 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.", 3673 should_resume, StateAsCString(state), 3674 was_restarted, stop_vote); 3675 3676 switch (stop_vote) 3677 { 3678 case eVoteYes: 3679 return_value = true; 3680 break; 3681 case eVoteNoOpinion: 3682 case eVoteNo: 3683 return_value = false; 3684 break; 3685 } 3686 3687 if (!was_restarted) 3688 { 3689 if (log) 3690 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", 3691 static_cast<void*>(event_ptr), 3692 StateAsCString(state)); 3693 ProcessEventData::SetRestartedInEvent(event_ptr, true); 3694 PrivateResume (); 3695 } 3696 3697 } 3698 else 3699 { 3700 return_value = true; 3701 SynchronouslyNotifyStateChanged (state); 3702 } 3703 } 3704 } 3705 break; 3706 } 3707 3708 // Forcing the next event delivery is a one shot deal. So reset it here. 3709 m_force_next_event_delivery = false; 3710 3711 // We do some coalescing of events (for instance two consecutive running events get coalesced.) 3712 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state 3713 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done, 3714 // because the PublicState reflects the last event pulled off the queue, and there may be several 3715 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event 3716 // yet. m_last_broadcast_state gets updated here. 3717 3718 if (return_value) 3719 m_last_broadcast_state = state; 3720 3721 if (log) 3722 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s", 3723 static_cast<void*>(event_ptr), StateAsCString(state), 3724 StateAsCString(m_last_broadcast_state), 3725 return_value ? "YES" : "NO"); 3726 return return_value; 3727 } 3728 3729 3730 bool 3731 Process::StartPrivateStateThread (bool force) 3732 { 3733 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS)); 3734 3735 bool already_running = PrivateStateThreadIsValid (); 3736 if (log) 3737 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread"); 3738 3739 if (!force && already_running) 3740 return true; 3741 3742 // Create a thread that watches our internal state and controls which 3743 // events make it to clients (into the DCProcess event queue). 3744 char thread_name[1024]; 3745 3746 if (Host::MAX_THREAD_NAME_LENGTH <= 16) 3747 { 3748 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit. 3749 if (already_running) 3750 snprintf(thread_name, sizeof(thread_name), "intern-state-OV"); 3751 else 3752 snprintf(thread_name, sizeof(thread_name), "intern-state"); 3753 } 3754 else 3755 { 3756 if (already_running) 3757 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID()); 3758 else 3759 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID()); 3760 } 3761 3762 // Create the private state thread, and start it running. 3763 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL); 3764 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread); 3765 if (success) 3766 { 3767 ResumePrivateStateThread(); 3768 return true; 3769 } 3770 else 3771 return false; 3772 } 3773 3774 void 3775 Process::PausePrivateStateThread () 3776 { 3777 ControlPrivateStateThread (eBroadcastInternalStateControlPause); 3778 } 3779 3780 void 3781 Process::ResumePrivateStateThread () 3782 { 3783 ControlPrivateStateThread (eBroadcastInternalStateControlResume); 3784 } 3785 3786 void 3787 Process::StopPrivateStateThread () 3788 { 3789 if (PrivateStateThreadIsValid ()) 3790 ControlPrivateStateThread (eBroadcastInternalStateControlStop); 3791 else 3792 { 3793 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 3794 if (log) 3795 log->Printf ("Went to stop the private state thread, but it was already invalid."); 3796 } 3797 } 3798 3799 void 3800 Process::ControlPrivateStateThread (uint32_t signal) 3801 { 3802 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 3803 3804 assert (signal == eBroadcastInternalStateControlStop || 3805 signal == eBroadcastInternalStateControlPause || 3806 signal == eBroadcastInternalStateControlResume); 3807 3808 if (log) 3809 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal); 3810 3811 // Signal the private state thread. First we should copy this is case the 3812 // thread starts exiting since the private state thread will NULL this out 3813 // when it exits 3814 const lldb::thread_t private_state_thread = m_private_state_thread; 3815 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread)) 3816 { 3817 TimeValue timeout_time; 3818 bool timed_out; 3819 3820 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL); 3821 3822 timeout_time = TimeValue::Now(); 3823 timeout_time.OffsetWithSeconds(2); 3824 if (log) 3825 log->Printf ("Sending control event of type: %d.", signal); 3826 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out); 3827 m_private_state_control_wait.SetValue (false, eBroadcastNever); 3828 3829 if (signal == eBroadcastInternalStateControlStop) 3830 { 3831 if (timed_out) 3832 { 3833 Error error; 3834 Host::ThreadCancel (private_state_thread, &error); 3835 if (log) 3836 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString()); 3837 } 3838 else 3839 { 3840 if (log) 3841 log->Printf ("The control event killed the private state thread without having to cancel."); 3842 } 3843 3844 thread_result_t result = NULL; 3845 Host::ThreadJoin (private_state_thread, &result, NULL); 3846 m_private_state_thread = LLDB_INVALID_HOST_THREAD; 3847 } 3848 } 3849 else 3850 { 3851 if (log) 3852 log->Printf ("Private state thread already dead, no need to signal it to stop."); 3853 } 3854 } 3855 3856 void 3857 Process::SendAsyncInterrupt () 3858 { 3859 if (PrivateStateThreadIsValid()) 3860 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL); 3861 else 3862 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL); 3863 } 3864 3865 void 3866 Process::HandlePrivateEvent (EventSP &event_sp) 3867 { 3868 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3869 m_resume_requested = false; 3870 3871 m_currently_handling_event.SetValue(true, eBroadcastNever); 3872 3873 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 3874 3875 // First check to see if anybody wants a shot at this event: 3876 if (m_next_event_action_ap.get() != NULL) 3877 { 3878 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp); 3879 if (log) 3880 log->Printf ("Ran next event action, result was %d.", action_result); 3881 3882 switch (action_result) 3883 { 3884 case NextEventAction::eEventActionSuccess: 3885 SetNextEventAction(NULL); 3886 break; 3887 3888 case NextEventAction::eEventActionRetry: 3889 break; 3890 3891 case NextEventAction::eEventActionExit: 3892 // Handle Exiting Here. If we already got an exited event, 3893 // we should just propagate it. Otherwise, swallow this event, 3894 // and set our state to exit so the next event will kill us. 3895 if (new_state != eStateExited) 3896 { 3897 // FIXME: should cons up an exited event, and discard this one. 3898 SetExitStatus(0, m_next_event_action_ap->GetExitString()); 3899 m_currently_handling_event.SetValue(false, eBroadcastAlways); 3900 SetNextEventAction(NULL); 3901 return; 3902 } 3903 SetNextEventAction(NULL); 3904 break; 3905 } 3906 } 3907 3908 // See if we should broadcast this state to external clients? 3909 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get()); 3910 3911 if (should_broadcast) 3912 { 3913 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged); 3914 if (log) 3915 { 3916 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s", 3917 __FUNCTION__, 3918 GetID(), 3919 StateAsCString(new_state), 3920 StateAsCString (GetState ()), 3921 is_hijacked ? "hijacked" : "public"); 3922 } 3923 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get()); 3924 if (StateIsRunningState (new_state)) 3925 { 3926 // Only push the input handler if we aren't fowarding events, 3927 // as this means the curses GUI is in use... 3928 if (!GetTarget().GetDebugger().IsForwardingEvents()) 3929 PushProcessIOHandler (); 3930 m_iohandler_sync.SetValue(true, eBroadcastAlways); 3931 } 3932 else if (StateIsStoppedState(new_state, false)) 3933 { 3934 m_iohandler_sync.SetValue(false, eBroadcastNever); 3935 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) 3936 { 3937 // If the lldb_private::Debugger is handling the events, we don't 3938 // want to pop the process IOHandler here, we want to do it when 3939 // we receive the stopped event so we can carefully control when 3940 // the process IOHandler is popped because when we stop we want to 3941 // display some text stating how and why we stopped, then maybe some 3942 // process/thread/frame info, and then we want the "(lldb) " prompt 3943 // to show up. If we pop the process IOHandler here, then we will 3944 // cause the command interpreter to become the top IOHandler after 3945 // the process pops off and it will update its prompt right away... 3946 // See the Debugger.cpp file where it calls the function as 3947 // "process_sp->PopProcessIOHandler()" to see where I am talking about. 3948 // Otherwise we end up getting overlapping "(lldb) " prompts and 3949 // garbled output. 3950 // 3951 // If we aren't handling the events in the debugger (which is indicated 3952 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we 3953 // are hijacked, then we always pop the process IO handler manually. 3954 // Hijacking happens when the internal process state thread is running 3955 // thread plans, or when commands want to run in synchronous mode 3956 // and they call "process->WaitForProcessToStop()". An example of something 3957 // that will hijack the events is a simple expression: 3958 // 3959 // (lldb) expr (int)puts("hello") 3960 // 3961 // This will cause the internal process state thread to resume and halt 3962 // the process (and _it_ will hijack the eBroadcastBitStateChanged 3963 // events) and we do need the IO handler to be pushed and popped 3964 // correctly. 3965 3966 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false) 3967 PopProcessIOHandler (); 3968 } 3969 } 3970 3971 BroadcastEvent (event_sp); 3972 } 3973 else 3974 { 3975 if (log) 3976 { 3977 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false", 3978 __FUNCTION__, 3979 GetID(), 3980 StateAsCString(new_state), 3981 StateAsCString (GetState ())); 3982 } 3983 } 3984 m_currently_handling_event.SetValue(false, eBroadcastAlways); 3985 } 3986 3987 thread_result_t 3988 Process::PrivateStateThread (void *arg) 3989 { 3990 Process *proc = static_cast<Process*> (arg); 3991 thread_result_t result = proc->RunPrivateStateThread(); 3992 return result; 3993 } 3994 3995 thread_result_t 3996 Process::RunPrivateStateThread () 3997 { 3998 bool control_only = true; 3999 m_private_state_control_wait.SetValue (false, eBroadcastNever); 4000 4001 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 4002 if (log) 4003 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", 4004 __FUNCTION__, static_cast<void*>(this), GetID()); 4005 4006 bool exit_now = false; 4007 while (!exit_now) 4008 { 4009 EventSP event_sp; 4010 WaitForEventsPrivate (NULL, event_sp, control_only); 4011 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) 4012 { 4013 if (log) 4014 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d", 4015 __FUNCTION__, static_cast<void*>(this), GetID(), 4016 event_sp->GetType()); 4017 4018 switch (event_sp->GetType()) 4019 { 4020 case eBroadcastInternalStateControlStop: 4021 exit_now = true; 4022 break; // doing any internal state management below 4023 4024 case eBroadcastInternalStateControlPause: 4025 control_only = true; 4026 break; 4027 4028 case eBroadcastInternalStateControlResume: 4029 control_only = false; 4030 break; 4031 } 4032 4033 m_private_state_control_wait.SetValue (true, eBroadcastAlways); 4034 continue; 4035 } 4036 else if (event_sp->GetType() == eBroadcastBitInterrupt) 4037 { 4038 if (m_public_state.GetValue() == eStateAttaching) 4039 { 4040 if (log) 4041 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.", 4042 __FUNCTION__, static_cast<void*>(this), 4043 GetID()); 4044 BroadcastEvent (eBroadcastBitInterrupt, NULL); 4045 } 4046 else 4047 { 4048 if (log) 4049 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", 4050 __FUNCTION__, static_cast<void*>(this), 4051 GetID()); 4052 Halt(); 4053 } 4054 continue; 4055 } 4056 4057 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 4058 4059 if (internal_state != eStateInvalid) 4060 { 4061 if (m_clear_thread_plans_on_stop && 4062 StateIsStoppedState(internal_state, true)) 4063 { 4064 m_clear_thread_plans_on_stop = false; 4065 m_thread_list.DiscardThreadPlans(); 4066 } 4067 HandlePrivateEvent (event_sp); 4068 } 4069 4070 if (internal_state == eStateInvalid || 4071 internal_state == eStateExited || 4072 internal_state == eStateDetached ) 4073 { 4074 if (log) 4075 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...", 4076 __FUNCTION__, static_cast<void*>(this), GetID(), 4077 StateAsCString(internal_state)); 4078 4079 break; 4080 } 4081 } 4082 4083 // Verify log is still enabled before attempting to write to it... 4084 if (log) 4085 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", 4086 __FUNCTION__, static_cast<void*>(this), GetID()); 4087 4088 m_public_run_lock.SetStopped(); 4089 m_private_state_control_wait.SetValue (true, eBroadcastAlways); 4090 m_private_state_thread = LLDB_INVALID_HOST_THREAD; 4091 return NULL; 4092 } 4093 4094 //------------------------------------------------------------------ 4095 // Process Event Data 4096 //------------------------------------------------------------------ 4097 4098 Process::ProcessEventData::ProcessEventData () : 4099 EventData (), 4100 m_process_sp (), 4101 m_state (eStateInvalid), 4102 m_restarted (false), 4103 m_update_state (0), 4104 m_interrupted (false) 4105 { 4106 } 4107 4108 Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) : 4109 EventData (), 4110 m_process_sp (process_sp), 4111 m_state (state), 4112 m_restarted (false), 4113 m_update_state (0), 4114 m_interrupted (false) 4115 { 4116 } 4117 4118 Process::ProcessEventData::~ProcessEventData() 4119 { 4120 } 4121 4122 const ConstString & 4123 Process::ProcessEventData::GetFlavorString () 4124 { 4125 static ConstString g_flavor ("Process::ProcessEventData"); 4126 return g_flavor; 4127 } 4128 4129 const ConstString & 4130 Process::ProcessEventData::GetFlavor () const 4131 { 4132 return ProcessEventData::GetFlavorString (); 4133 } 4134 4135 void 4136 Process::ProcessEventData::DoOnRemoval (Event *event_ptr) 4137 { 4138 // This function gets called twice for each event, once when the event gets pulled 4139 // off of the private process event queue, and then any number of times, first when it gets pulled off of 4140 // the public event queue, then other times when we're pretending that this is where we stopped at the 4141 // end of expression evaluation. m_update_state is used to distinguish these 4142 // three cases; it is 0 when we're just pulling it off for private handling, 4143 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then. 4144 if (m_update_state != 1) 4145 return; 4146 4147 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr)); 4148 4149 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had 4150 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may 4151 // end up restarting the process. 4152 if (m_interrupted) 4153 return; 4154 4155 // If we're stopped and haven't restarted, then do the StopInfo actions here: 4156 if (m_state == eStateStopped && ! m_restarted) 4157 { 4158 ThreadList &curr_thread_list = m_process_sp->GetThreadList(); 4159 uint32_t num_threads = curr_thread_list.GetSize(); 4160 uint32_t idx; 4161 4162 // The actions might change one of the thread's stop_info's opinions about whether we should 4163 // stop the process, so we need to query that as we go. 4164 4165 // One other complication here, is that we try to catch any case where the target has run (except for expressions) 4166 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and 4167 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like 4168 // to also know if it has changed at all, so we make up a vector of the thread ID's and check what we get back 4169 // against this list & bag out if anything differs. 4170 std::vector<uint32_t> thread_index_array(num_threads); 4171 for (idx = 0; idx < num_threads; ++idx) 4172 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID(); 4173 4174 // Use this to track whether we should continue from here. We will only continue the target running if 4175 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running, 4176 // then it doesn't matter what the other threads say... 4177 4178 bool still_should_stop = false; 4179 4180 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a 4181 // valid stop reason. In that case we should just stop, because we have no way of telling what the right 4182 // thing to do is, and it's better to let the user decide than continue behind their backs. 4183 4184 bool does_anybody_have_an_opinion = false; 4185 4186 for (idx = 0; idx < num_threads; ++idx) 4187 { 4188 curr_thread_list = m_process_sp->GetThreadList(); 4189 if (curr_thread_list.GetSize() != num_threads) 4190 { 4191 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS)); 4192 if (log) 4193 log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize()); 4194 break; 4195 } 4196 4197 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx); 4198 4199 if (thread_sp->GetIndexID() != thread_index_array[idx]) 4200 { 4201 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS)); 4202 if (log) 4203 log->Printf("The thread at position %u changed from %u to %u while processing event.", 4204 idx, 4205 thread_index_array[idx], 4206 thread_sp->GetIndexID()); 4207 break; 4208 } 4209 4210 StopInfoSP stop_info_sp = thread_sp->GetStopInfo (); 4211 if (stop_info_sp && stop_info_sp->IsValid()) 4212 { 4213 does_anybody_have_an_opinion = true; 4214 bool this_thread_wants_to_stop; 4215 if (stop_info_sp->GetOverrideShouldStop()) 4216 { 4217 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue(); 4218 } 4219 else 4220 { 4221 stop_info_sp->PerformAction(event_ptr); 4222 // The stop action might restart the target. If it does, then we want to mark that in the 4223 // event so that whoever is receiving it will know to wait for the running event and reflect 4224 // that state appropriately. 4225 // We also need to stop processing actions, since they aren't expecting the target to be running. 4226 4227 // FIXME: we might have run. 4228 if (stop_info_sp->HasTargetRunSinceMe()) 4229 { 4230 SetRestarted (true); 4231 break; 4232 } 4233 4234 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr); 4235 } 4236 4237 if (still_should_stop == false) 4238 still_should_stop = this_thread_wants_to_stop; 4239 } 4240 } 4241 4242 4243 if (!GetRestarted()) 4244 { 4245 if (!still_should_stop && does_anybody_have_an_opinion) 4246 { 4247 // We've been asked to continue, so do that here. 4248 SetRestarted(true); 4249 // Use the public resume method here, since this is just 4250 // extending a public resume. 4251 m_process_sp->PrivateResume(); 4252 } 4253 else 4254 { 4255 // If we didn't restart, run the Stop Hooks here: 4256 // They might also restart the target, so watch for that. 4257 m_process_sp->GetTarget().RunStopHooks(); 4258 if (m_process_sp->GetPrivateState() == eStateRunning) 4259 SetRestarted(true); 4260 } 4261 } 4262 } 4263 } 4264 4265 void 4266 Process::ProcessEventData::Dump (Stream *s) const 4267 { 4268 if (m_process_sp) 4269 s->Printf(" process = %p (pid = %" PRIu64 "), ", 4270 static_cast<void*>(m_process_sp.get()), m_process_sp->GetID()); 4271 4272 s->Printf("state = %s", StateAsCString(GetState())); 4273 } 4274 4275 const Process::ProcessEventData * 4276 Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr) 4277 { 4278 if (event_ptr) 4279 { 4280 const EventData *event_data = event_ptr->GetData(); 4281 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString()) 4282 return static_cast <const ProcessEventData *> (event_ptr->GetData()); 4283 } 4284 return NULL; 4285 } 4286 4287 ProcessSP 4288 Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr) 4289 { 4290 ProcessSP process_sp; 4291 const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 4292 if (data) 4293 process_sp = data->GetProcessSP(); 4294 return process_sp; 4295 } 4296 4297 StateType 4298 Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr) 4299 { 4300 const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 4301 if (data == NULL) 4302 return eStateInvalid; 4303 else 4304 return data->GetState(); 4305 } 4306 4307 bool 4308 Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr) 4309 { 4310 const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 4311 if (data == NULL) 4312 return false; 4313 else 4314 return data->GetRestarted(); 4315 } 4316 4317 void 4318 Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value) 4319 { 4320 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 4321 if (data != NULL) 4322 data->SetRestarted(new_value); 4323 } 4324 4325 size_t 4326 Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) 4327 { 4328 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 4329 if (data != NULL) 4330 return data->GetNumRestartedReasons(); 4331 else 4332 return 0; 4333 } 4334 4335 const char * 4336 Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx) 4337 { 4338 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 4339 if (data != NULL) 4340 return data->GetRestartedReasonAtIndex(idx); 4341 else 4342 return NULL; 4343 } 4344 4345 void 4346 Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason) 4347 { 4348 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 4349 if (data != NULL) 4350 data->AddRestartedReason(reason); 4351 } 4352 4353 bool 4354 Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr) 4355 { 4356 const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 4357 if (data == NULL) 4358 return false; 4359 else 4360 return data->GetInterrupted (); 4361 } 4362 4363 void 4364 Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value) 4365 { 4366 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 4367 if (data != NULL) 4368 data->SetInterrupted(new_value); 4369 } 4370 4371 bool 4372 Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr) 4373 { 4374 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 4375 if (data) 4376 { 4377 data->SetUpdateStateOnRemoval(); 4378 return true; 4379 } 4380 return false; 4381 } 4382 4383 lldb::TargetSP 4384 Process::CalculateTarget () 4385 { 4386 return m_target.shared_from_this(); 4387 } 4388 4389 void 4390 Process::CalculateExecutionContext (ExecutionContext &exe_ctx) 4391 { 4392 exe_ctx.SetTargetPtr (&m_target); 4393 exe_ctx.SetProcessPtr (this); 4394 exe_ctx.SetThreadPtr(NULL); 4395 exe_ctx.SetFramePtr (NULL); 4396 } 4397 4398 //uint32_t 4399 //Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids) 4400 //{ 4401 // return 0; 4402 //} 4403 // 4404 //ArchSpec 4405 //Process::GetArchSpecForExistingProcess (lldb::pid_t pid) 4406 //{ 4407 // return Host::GetArchSpecForExistingProcess (pid); 4408 //} 4409 // 4410 //ArchSpec 4411 //Process::GetArchSpecForExistingProcess (const char *process_name) 4412 //{ 4413 // return Host::GetArchSpecForExistingProcess (process_name); 4414 //} 4415 // 4416 void 4417 Process::AppendSTDOUT (const char * s, size_t len) 4418 { 4419 Mutex::Locker locker (m_stdio_communication_mutex); 4420 m_stdout_data.append (s, len); 4421 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState())); 4422 } 4423 4424 void 4425 Process::AppendSTDERR (const char * s, size_t len) 4426 { 4427 Mutex::Locker locker (m_stdio_communication_mutex); 4428 m_stderr_data.append (s, len); 4429 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState())); 4430 } 4431 4432 void 4433 Process::BroadcastAsyncProfileData(const std::string &one_profile_data) 4434 { 4435 Mutex::Locker locker (m_profile_data_comm_mutex); 4436 m_profile_data.push_back(one_profile_data); 4437 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState())); 4438 } 4439 4440 size_t 4441 Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error) 4442 { 4443 Mutex::Locker locker(m_profile_data_comm_mutex); 4444 if (m_profile_data.empty()) 4445 return 0; 4446 4447 std::string &one_profile_data = m_profile_data.front(); 4448 size_t bytes_available = one_profile_data.size(); 4449 if (bytes_available > 0) 4450 { 4451 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 4452 if (log) 4453 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", 4454 static_cast<void*>(buf), 4455 static_cast<uint64_t>(buf_size)); 4456 if (bytes_available > buf_size) 4457 { 4458 memcpy(buf, one_profile_data.c_str(), buf_size); 4459 one_profile_data.erase(0, buf_size); 4460 bytes_available = buf_size; 4461 } 4462 else 4463 { 4464 memcpy(buf, one_profile_data.c_str(), bytes_available); 4465 m_profile_data.erase(m_profile_data.begin()); 4466 } 4467 } 4468 return bytes_available; 4469 } 4470 4471 4472 //------------------------------------------------------------------ 4473 // Process STDIO 4474 //------------------------------------------------------------------ 4475 4476 size_t 4477 Process::GetSTDOUT (char *buf, size_t buf_size, Error &error) 4478 { 4479 Mutex::Locker locker(m_stdio_communication_mutex); 4480 size_t bytes_available = m_stdout_data.size(); 4481 if (bytes_available > 0) 4482 { 4483 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 4484 if (log) 4485 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", 4486 static_cast<void*>(buf), 4487 static_cast<uint64_t>(buf_size)); 4488 if (bytes_available > buf_size) 4489 { 4490 memcpy(buf, m_stdout_data.c_str(), buf_size); 4491 m_stdout_data.erase(0, buf_size); 4492 bytes_available = buf_size; 4493 } 4494 else 4495 { 4496 memcpy(buf, m_stdout_data.c_str(), bytes_available); 4497 m_stdout_data.clear(); 4498 } 4499 } 4500 return bytes_available; 4501 } 4502 4503 4504 size_t 4505 Process::GetSTDERR (char *buf, size_t buf_size, Error &error) 4506 { 4507 Mutex::Locker locker(m_stdio_communication_mutex); 4508 size_t bytes_available = m_stderr_data.size(); 4509 if (bytes_available > 0) 4510 { 4511 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 4512 if (log) 4513 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", 4514 static_cast<void*>(buf), 4515 static_cast<uint64_t>(buf_size)); 4516 if (bytes_available > buf_size) 4517 { 4518 memcpy(buf, m_stderr_data.c_str(), buf_size); 4519 m_stderr_data.erase(0, buf_size); 4520 bytes_available = buf_size; 4521 } 4522 else 4523 { 4524 memcpy(buf, m_stderr_data.c_str(), bytes_available); 4525 m_stderr_data.clear(); 4526 } 4527 } 4528 return bytes_available; 4529 } 4530 4531 void 4532 Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len) 4533 { 4534 Process *process = (Process *) baton; 4535 process->AppendSTDOUT (static_cast<const char *>(src), src_len); 4536 } 4537 4538 class IOHandlerProcessSTDIO : 4539 public IOHandler 4540 { 4541 public: 4542 IOHandlerProcessSTDIO (Process *process, 4543 int write_fd) : 4544 IOHandler(process->GetTarget().GetDebugger()), 4545 m_process (process), 4546 m_read_file (), 4547 m_write_file (write_fd, false), 4548 m_pipe () 4549 { 4550 m_read_file.SetDescriptor(GetInputFD(), false); 4551 } 4552 4553 virtual 4554 ~IOHandlerProcessSTDIO () 4555 { 4556 4557 } 4558 4559 bool 4560 OpenPipes () 4561 { 4562 if (m_pipe.IsValid()) 4563 return true; 4564 return m_pipe.Open(); 4565 } 4566 4567 void 4568 ClosePipes() 4569 { 4570 m_pipe.Close(); 4571 } 4572 4573 // Each IOHandler gets to run until it is done. It should read data 4574 // from the "in" and place output into "out" and "err and return 4575 // when done. 4576 virtual void 4577 Run () 4578 { 4579 if (m_read_file.IsValid() && m_write_file.IsValid()) 4580 { 4581 SetIsDone(false); 4582 if (OpenPipes()) 4583 { 4584 const int read_fd = m_read_file.GetDescriptor(); 4585 const int pipe_read_fd = m_pipe.GetReadFileDescriptor(); 4586 TerminalState terminal_state; 4587 terminal_state.Save (read_fd, false); 4588 Terminal terminal(read_fd); 4589 terminal.SetCanonical(false); 4590 terminal.SetEcho(false); 4591 // FD_ZERO, FD_SET are not supported on windows 4592 #ifndef _WIN32 4593 while (!GetIsDone()) 4594 { 4595 fd_set read_fdset; 4596 FD_ZERO (&read_fdset); 4597 FD_SET (read_fd, &read_fdset); 4598 FD_SET (pipe_read_fd, &read_fdset); 4599 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1; 4600 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL); 4601 if (num_set_fds < 0) 4602 { 4603 const int select_errno = errno; 4604 4605 if (select_errno != EINTR) 4606 SetIsDone(true); 4607 } 4608 else if (num_set_fds > 0) 4609 { 4610 char ch = 0; 4611 size_t n; 4612 if (FD_ISSET (read_fd, &read_fdset)) 4613 { 4614 n = 1; 4615 if (m_read_file.Read(&ch, n).Success() && n == 1) 4616 { 4617 if (m_write_file.Write(&ch, n).Fail() || n != 1) 4618 SetIsDone(true); 4619 } 4620 else 4621 SetIsDone(true); 4622 } 4623 if (FD_ISSET (pipe_read_fd, &read_fdset)) 4624 { 4625 // Consume the interrupt byte 4626 if (m_pipe.Read (&ch, 1) == 1) 4627 { 4628 switch (ch) 4629 { 4630 case 'q': 4631 SetIsDone(true); 4632 break; 4633 case 'i': 4634 if (StateIsRunningState(m_process->GetState())) 4635 m_process->Halt(); 4636 break; 4637 } 4638 } 4639 } 4640 } 4641 } 4642 #endif 4643 terminal_state.Restore(); 4644 4645 } 4646 else 4647 SetIsDone(true); 4648 } 4649 else 4650 SetIsDone(true); 4651 } 4652 4653 // Hide any characters that have been displayed so far so async 4654 // output can be displayed. Refresh() will be called after the 4655 // output has been displayed. 4656 virtual void 4657 Hide () 4658 { 4659 4660 } 4661 // Called when the async output has been received in order to update 4662 // the input reader (refresh the prompt and redisplay any current 4663 // line(s) that are being edited 4664 virtual void 4665 Refresh () 4666 { 4667 4668 } 4669 4670 virtual void 4671 Cancel () 4672 { 4673 char ch = 'q'; // Send 'q' for quit 4674 m_pipe.Write (&ch, 1); 4675 } 4676 4677 virtual bool 4678 Interrupt () 4679 { 4680 // Do only things that are safe to do in an interrupt context (like in 4681 // a SIGINT handler), like write 1 byte to a file descriptor. This will 4682 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte 4683 // that was written to the pipe and then call m_process->Halt() from a 4684 // much safer location in code. 4685 if (m_active) 4686 { 4687 char ch = 'i'; // Send 'i' for interrupt 4688 return m_pipe.Write (&ch, 1) == 1; 4689 } 4690 else 4691 { 4692 // This IOHandler might be pushed on the stack, but not being run currently 4693 // so do the right thing if we aren't actively watching for STDIN by sending 4694 // the interrupt to the process. Otherwise the write to the pipe above would 4695 // do nothing. This can happen when the command interpreter is running and 4696 // gets a "expression ...". It will be on the IOHandler thread and sending 4697 // the input is complete to the delegate which will cause the expression to 4698 // run, which will push the process IO handler, but not run it. 4699 4700 if (StateIsRunningState(m_process->GetState())) 4701 { 4702 m_process->SendAsyncInterrupt(); 4703 return true; 4704 } 4705 } 4706 return false; 4707 } 4708 4709 virtual void 4710 GotEOF() 4711 { 4712 4713 } 4714 4715 protected: 4716 Process *m_process; 4717 File m_read_file; // Read from this file (usually actual STDIN for LLDB 4718 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee) 4719 Pipe m_pipe; 4720 }; 4721 4722 void 4723 Process::SetSTDIOFileDescriptor (int fd) 4724 { 4725 // First set up the Read Thread for reading/handling process I/O 4726 4727 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true)); 4728 4729 if (conn_ap.get()) 4730 { 4731 m_stdio_communication.SetConnection (conn_ap.release()); 4732 if (m_stdio_communication.IsConnected()) 4733 { 4734 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this); 4735 m_stdio_communication.StartReadThread(); 4736 4737 // Now read thread is set up, set up input reader. 4738 4739 if (!m_process_input_reader.get()) 4740 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd)); 4741 } 4742 } 4743 } 4744 4745 bool 4746 Process::ProcessIOHandlerIsActive () 4747 { 4748 IOHandlerSP io_handler_sp (m_process_input_reader); 4749 if (io_handler_sp) 4750 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp); 4751 return false; 4752 } 4753 bool 4754 Process::PushProcessIOHandler () 4755 { 4756 IOHandlerSP io_handler_sp (m_process_input_reader); 4757 if (io_handler_sp) 4758 { 4759 io_handler_sp->SetIsDone(false); 4760 m_target.GetDebugger().PushIOHandler (io_handler_sp); 4761 return true; 4762 } 4763 return false; 4764 } 4765 4766 bool 4767 Process::PopProcessIOHandler () 4768 { 4769 IOHandlerSP io_handler_sp (m_process_input_reader); 4770 if (io_handler_sp) 4771 return m_target.GetDebugger().PopIOHandler (io_handler_sp); 4772 return false; 4773 } 4774 4775 // The process needs to know about installed plug-ins 4776 void 4777 Process::SettingsInitialize () 4778 { 4779 Thread::SettingsInitialize (); 4780 } 4781 4782 void 4783 Process::SettingsTerminate () 4784 { 4785 Thread::SettingsTerminate (); 4786 } 4787 4788 ExpressionResults 4789 Process::RunThreadPlan (ExecutionContext &exe_ctx, 4790 lldb::ThreadPlanSP &thread_plan_sp, 4791 const EvaluateExpressionOptions &options, 4792 Stream &errors) 4793 { 4794 ExpressionResults return_value = eExpressionSetupError; 4795 4796 if (thread_plan_sp.get() == NULL) 4797 { 4798 errors.Printf("RunThreadPlan called with empty thread plan."); 4799 return eExpressionSetupError; 4800 } 4801 4802 if (!thread_plan_sp->ValidatePlan(NULL)) 4803 { 4804 errors.Printf ("RunThreadPlan called with an invalid thread plan."); 4805 return eExpressionSetupError; 4806 } 4807 4808 if (exe_ctx.GetProcessPtr() != this) 4809 { 4810 errors.Printf("RunThreadPlan called on wrong process."); 4811 return eExpressionSetupError; 4812 } 4813 4814 Thread *thread = exe_ctx.GetThreadPtr(); 4815 if (thread == NULL) 4816 { 4817 errors.Printf("RunThreadPlan called with invalid thread."); 4818 return eExpressionSetupError; 4819 } 4820 4821 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes. 4822 // For that to be true the plan can't be private - since private plans suppress themselves in the 4823 // GetCompletedPlan call. 4824 4825 bool orig_plan_private = thread_plan_sp->GetPrivate(); 4826 thread_plan_sp->SetPrivate(false); 4827 4828 if (m_private_state.GetValue() != eStateStopped) 4829 { 4830 errors.Printf ("RunThreadPlan called while the private state was not stopped."); 4831 return eExpressionSetupError; 4832 } 4833 4834 // Save the thread & frame from the exe_ctx for restoration after we run 4835 const uint32_t thread_idx_id = thread->GetIndexID(); 4836 StackFrameSP selected_frame_sp = thread->GetSelectedFrame(); 4837 if (!selected_frame_sp) 4838 { 4839 thread->SetSelectedFrame(0); 4840 selected_frame_sp = thread->GetSelectedFrame(); 4841 if (!selected_frame_sp) 4842 { 4843 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id); 4844 return eExpressionSetupError; 4845 } 4846 } 4847 4848 StackID ctx_frame_id = selected_frame_sp->GetStackID(); 4849 4850 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either, 4851 // so we should arrange to reset them as well. 4852 4853 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread(); 4854 4855 uint32_t selected_tid; 4856 StackID selected_stack_id; 4857 if (selected_thread_sp) 4858 { 4859 selected_tid = selected_thread_sp->GetIndexID(); 4860 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID(); 4861 } 4862 else 4863 { 4864 selected_tid = LLDB_INVALID_THREAD_ID; 4865 } 4866 4867 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD; 4868 lldb::StateType old_state; 4869 lldb::ThreadPlanSP stopper_base_plan_sp; 4870 4871 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS)); 4872 if (Host::GetCurrentThread() == m_private_state_thread) 4873 { 4874 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since 4875 // we are the thread that is generating public events. 4876 // The simplest thing to do is to spin up a temporary thread to handle private state thread events while 4877 // we are fielding public events here. 4878 if (log) 4879 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events."); 4880 4881 backup_private_state_thread = m_private_state_thread; 4882 4883 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop, 4884 // returning control here. 4885 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop 4886 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack 4887 // before the plan we want to run. Since base plans always stop and return control to the user, that will 4888 // do just what we want. 4889 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread)); 4890 thread->QueueThreadPlan (stopper_base_plan_sp, false); 4891 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly. 4892 old_state = m_public_state.GetValue(); 4893 m_public_state.SetValueNoLock(eStateStopped); 4894 4895 // Now spin up the private state thread: 4896 StartPrivateStateThread(true); 4897 } 4898 4899 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense? 4900 4901 if (options.GetDebug()) 4902 { 4903 // In this case, we aren't actually going to run, we just want to stop right away. 4904 // Flush this thread so we will refetch the stacks and show the correct backtrace. 4905 // FIXME: To make this prettier we should invent some stop reason for this, but that 4906 // is only cosmetic, and this functionality is only of use to lldb developers who can 4907 // live with not pretty... 4908 thread->Flush(); 4909 return eExpressionStoppedForDebug; 4910 } 4911 4912 Listener listener("lldb.process.listener.run-thread-plan"); 4913 4914 lldb::EventSP event_to_broadcast_sp; 4915 4916 { 4917 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get 4918 // restored on exit to the function. 4919 // 4920 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event 4921 // is put into event_to_broadcast_sp for rebroadcasting. 4922 4923 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener); 4924 4925 if (log) 4926 { 4927 StreamString s; 4928 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose); 4929 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".", 4930 thread->GetIndexID(), 4931 thread->GetID(), 4932 s.GetData()); 4933 } 4934 4935 bool got_event; 4936 lldb::EventSP event_sp; 4937 lldb::StateType stop_state = lldb::eStateInvalid; 4938 4939 TimeValue* timeout_ptr = NULL; 4940 TimeValue real_timeout; 4941 4942 bool before_first_timeout = true; // This is set to false the first time that we have to halt the target. 4943 bool do_resume = true; 4944 bool handle_running_event = true; 4945 const uint64_t default_one_thread_timeout_usec = 250000; 4946 4947 // This is just for accounting: 4948 uint32_t num_resumes = 0; 4949 4950 uint32_t timeout_usec = options.GetTimeoutUsec(); 4951 uint32_t one_thread_timeout_usec; 4952 uint32_t all_threads_timeout_usec = 0; 4953 4954 // If we are going to run all threads the whole time, or if we are only going to run one thread, 4955 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the 4956 // first timeout already. 4957 4958 if (!options.GetStopOthers() || !options.GetTryAllThreads()) 4959 { 4960 before_first_timeout = false; 4961 one_thread_timeout_usec = 0; 4962 all_threads_timeout_usec = timeout_usec; 4963 } 4964 else 4965 { 4966 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec(); 4967 4968 // If the overall wait is forever, then we only need to set the one thread timeout: 4969 if (timeout_usec == 0) 4970 { 4971 if (option_one_thread_timeout != 0) 4972 one_thread_timeout_usec = option_one_thread_timeout; 4973 else 4974 one_thread_timeout_usec = default_one_thread_timeout_usec; 4975 } 4976 else 4977 { 4978 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout, 4979 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec. 4980 uint64_t computed_one_thread_timeout; 4981 if (option_one_thread_timeout != 0) 4982 { 4983 if (timeout_usec < option_one_thread_timeout) 4984 { 4985 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout"); 4986 return eExpressionSetupError; 4987 } 4988 computed_one_thread_timeout = option_one_thread_timeout; 4989 } 4990 else 4991 { 4992 computed_one_thread_timeout = timeout_usec / 2; 4993 if (computed_one_thread_timeout > default_one_thread_timeout_usec) 4994 computed_one_thread_timeout = default_one_thread_timeout_usec; 4995 } 4996 one_thread_timeout_usec = computed_one_thread_timeout; 4997 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec; 4998 4999 } 5000 } 5001 5002 if (log) 5003 log->Printf ("Stop others: %u, try all: %u, before_first: %u, one thread: %" PRIu32 " - all threads: %" PRIu32 ".\n", 5004 options.GetStopOthers(), 5005 options.GetTryAllThreads(), 5006 before_first_timeout, 5007 one_thread_timeout_usec, 5008 all_threads_timeout_usec); 5009 5010 // This isn't going to work if there are unfetched events on the queue. 5011 // Are there cases where we might want to run the remaining events here, and then try to 5012 // call the function? That's probably being too tricky for our own good. 5013 5014 Event *other_events = listener.PeekAtNextEvent(); 5015 if (other_events != NULL) 5016 { 5017 errors.Printf("Calling RunThreadPlan with pending events on the queue."); 5018 return eExpressionSetupError; 5019 } 5020 5021 // We also need to make sure that the next event is delivered. We might be calling a function as part of 5022 // a thread plan, in which case the last delivered event could be the running event, and we don't want 5023 // event coalescing to cause us to lose OUR running event... 5024 ForceNextEventDelivery(); 5025 5026 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done. 5027 // So don't call return anywhere within it. 5028 5029 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT 5030 // It's pretty much impossible to write test cases for things like: 5031 // One thread timeout expires, I go to halt, but the process already stopped 5032 // on the function call stop breakpoint. Turning on this define will make us not 5033 // fetch the first event till after the halt. So if you run a quick function, it will have 5034 // completed, and the completion event will be waiting, when you interrupt for halt. 5035 // The expression evaluation should still succeed. 5036 bool miss_first_event = true; 5037 #endif 5038 TimeValue one_thread_timeout; 5039 TimeValue final_timeout; 5040 5041 5042 while (1) 5043 { 5044 // We usually want to resume the process if we get to the top of the loop. 5045 // The only exception is if we get two running events with no intervening 5046 // stop, which can happen, we will just wait for then next stop event. 5047 if (log) 5048 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.", 5049 do_resume, 5050 handle_running_event, 5051 before_first_timeout); 5052 5053 if (do_resume || handle_running_event) 5054 { 5055 // Do the initial resume and wait for the running event before going further. 5056 5057 if (do_resume) 5058 { 5059 num_resumes++; 5060 Error resume_error = PrivateResume (); 5061 if (!resume_error.Success()) 5062 { 5063 errors.Printf("Error resuming inferior the %d time: \"%s\".\n", 5064 num_resumes, 5065 resume_error.AsCString()); 5066 return_value = eExpressionSetupError; 5067 break; 5068 } 5069 } 5070 5071 TimeValue resume_timeout = TimeValue::Now(); 5072 resume_timeout.OffsetWithMicroSeconds(500000); 5073 5074 got_event = listener.WaitForEvent(&resume_timeout, event_sp); 5075 if (!got_event) 5076 { 5077 if (log) 5078 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.", 5079 num_resumes); 5080 5081 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes); 5082 return_value = eExpressionSetupError; 5083 break; 5084 } 5085 5086 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 5087 5088 if (stop_state != eStateRunning) 5089 { 5090 bool restarted = false; 5091 5092 if (stop_state == eStateStopped) 5093 { 5094 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()); 5095 if (log) 5096 log->Printf("Process::RunThreadPlan(): didn't get running event after " 5097 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).", 5098 num_resumes, 5099 StateAsCString(stop_state), 5100 restarted, 5101 do_resume, 5102 handle_running_event); 5103 } 5104 5105 if (restarted) 5106 { 5107 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted 5108 // event here. But if I do, the best thing is to Halt and then get out of here. 5109 Halt(); 5110 } 5111 5112 errors.Printf("Didn't get running event after initial resume, got %s instead.", 5113 StateAsCString(stop_state)); 5114 return_value = eExpressionSetupError; 5115 break; 5116 } 5117 5118 if (log) 5119 log->PutCString ("Process::RunThreadPlan(): resuming succeeded."); 5120 // We need to call the function synchronously, so spin waiting for it to return. 5121 // If we get interrupted while executing, we're going to lose our context, and 5122 // won't be able to gather the result at this point. 5123 // We set the timeout AFTER the resume, since the resume takes some time and we 5124 // don't want to charge that to the timeout. 5125 } 5126 else 5127 { 5128 if (log) 5129 log->PutCString ("Process::RunThreadPlan(): waiting for next event."); 5130 } 5131 5132 if (before_first_timeout) 5133 { 5134 if (options.GetTryAllThreads()) 5135 { 5136 one_thread_timeout = TimeValue::Now(); 5137 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec); 5138 timeout_ptr = &one_thread_timeout; 5139 } 5140 else 5141 { 5142 if (timeout_usec == 0) 5143 timeout_ptr = NULL; 5144 else 5145 { 5146 final_timeout = TimeValue::Now(); 5147 final_timeout.OffsetWithMicroSeconds (timeout_usec); 5148 timeout_ptr = &final_timeout; 5149 } 5150 } 5151 } 5152 else 5153 { 5154 if (timeout_usec == 0) 5155 timeout_ptr = NULL; 5156 else 5157 { 5158 final_timeout = TimeValue::Now(); 5159 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec); 5160 timeout_ptr = &final_timeout; 5161 } 5162 } 5163 5164 do_resume = true; 5165 handle_running_event = true; 5166 5167 // Now wait for the process to stop again: 5168 event_sp.reset(); 5169 5170 if (log) 5171 { 5172 if (timeout_ptr) 5173 { 5174 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64, 5175 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(), 5176 timeout_ptr->GetAsMicroSecondsSinceJan1_1970()); 5177 } 5178 else 5179 { 5180 log->Printf ("Process::RunThreadPlan(): about to wait forever."); 5181 } 5182 } 5183 5184 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT 5185 // See comment above... 5186 if (miss_first_event) 5187 { 5188 usleep(1000); 5189 miss_first_event = false; 5190 got_event = false; 5191 } 5192 else 5193 #endif 5194 got_event = listener.WaitForEvent (timeout_ptr, event_sp); 5195 5196 if (got_event) 5197 { 5198 if (event_sp.get()) 5199 { 5200 bool keep_going = false; 5201 if (event_sp->GetType() == eBroadcastBitInterrupt) 5202 { 5203 Halt(); 5204 return_value = eExpressionInterrupted; 5205 errors.Printf ("Execution halted by user interrupt."); 5206 if (log) 5207 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting."); 5208 break; 5209 } 5210 else 5211 { 5212 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 5213 if (log) 5214 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state)); 5215 5216 switch (stop_state) 5217 { 5218 case lldb::eStateStopped: 5219 { 5220 // We stopped, figure out what we are going to do now. 5221 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id); 5222 if (!thread_sp) 5223 { 5224 // Ooh, our thread has vanished. Unlikely that this was successful execution... 5225 if (log) 5226 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id); 5227 return_value = eExpressionInterrupted; 5228 } 5229 else 5230 { 5231 // If we were restarted, we just need to go back up to fetch another event. 5232 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) 5233 { 5234 if (log) 5235 { 5236 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting."); 5237 } 5238 keep_going = true; 5239 do_resume = false; 5240 handle_running_event = true; 5241 5242 } 5243 else 5244 { 5245 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ()); 5246 StopReason stop_reason = eStopReasonInvalid; 5247 if (stop_info_sp) 5248 stop_reason = stop_info_sp->GetStopReason(); 5249 5250 // FIXME: We only check if the stop reason is plan complete, should we make sure that 5251 // it is OUR plan that is complete? 5252 if (stop_reason == eStopReasonPlanComplete) 5253 { 5254 if (log) 5255 log->PutCString ("Process::RunThreadPlan(): execution completed successfully."); 5256 // Now mark this plan as private so it doesn't get reported as the stop reason 5257 // after this point. 5258 if (thread_plan_sp) 5259 thread_plan_sp->SetPrivate (orig_plan_private); 5260 return_value = eExpressionCompleted; 5261 } 5262 else 5263 { 5264 // Something restarted the target, so just wait for it to stop for real. 5265 if (stop_reason == eStopReasonBreakpoint) 5266 { 5267 if (log) 5268 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription()); 5269 return_value = eExpressionHitBreakpoint; 5270 if (!options.DoesIgnoreBreakpoints()) 5271 { 5272 event_to_broadcast_sp = event_sp; 5273 } 5274 } 5275 else 5276 { 5277 if (log) 5278 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete."); 5279 if (!options.DoesUnwindOnError()) 5280 event_to_broadcast_sp = event_sp; 5281 return_value = eExpressionInterrupted; 5282 } 5283 } 5284 } 5285 } 5286 } 5287 break; 5288 5289 case lldb::eStateRunning: 5290 // This shouldn't really happen, but sometimes we do get two running events without an 5291 // intervening stop, and in that case we should just go back to waiting for the stop. 5292 do_resume = false; 5293 keep_going = true; 5294 handle_running_event = false; 5295 break; 5296 5297 default: 5298 if (log) 5299 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state)); 5300 5301 if (stop_state == eStateExited) 5302 event_to_broadcast_sp = event_sp; 5303 5304 errors.Printf ("Execution stopped with unexpected state.\n"); 5305 return_value = eExpressionInterrupted; 5306 break; 5307 } 5308 } 5309 5310 if (keep_going) 5311 continue; 5312 else 5313 break; 5314 } 5315 else 5316 { 5317 if (log) 5318 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd..."); 5319 return_value = eExpressionInterrupted; 5320 break; 5321 } 5322 } 5323 else 5324 { 5325 // If we didn't get an event that means we've timed out... 5326 // We will interrupt the process here. Depending on what we were asked to do we will 5327 // either exit, or try with all threads running for the same timeout. 5328 5329 if (log) { 5330 if (options.GetTryAllThreads()) 5331 { 5332 if (before_first_timeout) 5333 { 5334 if (timeout_usec != 0) 5335 { 5336 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, " 5337 "running for %" PRIu32 " usec with all threads enabled.", 5338 all_threads_timeout_usec); 5339 } 5340 else 5341 { 5342 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, " 5343 "running forever with all threads enabled."); 5344 } 5345 } 5346 else 5347 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled " 5348 "and timeout: %u timed out, abandoning execution.", 5349 timeout_usec); 5350 } 5351 else 5352 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, " 5353 "abandoning execution.", 5354 timeout_usec); 5355 } 5356 5357 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target 5358 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event. 5359 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In 5360 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's 5361 // stopped event. That's what this while loop does. 5362 5363 bool back_to_top = true; 5364 uint32_t try_halt_again = 0; 5365 bool do_halt = true; 5366 const uint32_t num_retries = 5; 5367 while (try_halt_again < num_retries) 5368 { 5369 Error halt_error; 5370 if (do_halt) 5371 { 5372 if (log) 5373 log->Printf ("Process::RunThreadPlan(): Running Halt."); 5374 halt_error = Halt(); 5375 } 5376 if (halt_error.Success()) 5377 { 5378 if (log) 5379 log->PutCString ("Process::RunThreadPlan(): Halt succeeded."); 5380 5381 real_timeout = TimeValue::Now(); 5382 real_timeout.OffsetWithMicroSeconds(500000); 5383 5384 got_event = listener.WaitForEvent(&real_timeout, event_sp); 5385 5386 if (got_event) 5387 { 5388 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 5389 if (log) 5390 { 5391 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state)); 5392 if (stop_state == lldb::eStateStopped 5393 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get())) 5394 log->PutCString (" Event was the Halt interruption event."); 5395 } 5396 5397 if (stop_state == lldb::eStateStopped) 5398 { 5399 // Between the time we initiated the Halt and the time we delivered it, the process could have 5400 // already finished its job. Check that here: 5401 5402 if (thread->IsThreadPlanDone (thread_plan_sp.get())) 5403 { 5404 if (log) 5405 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. " 5406 "Exiting wait loop."); 5407 return_value = eExpressionCompleted; 5408 back_to_top = false; 5409 break; 5410 } 5411 5412 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) 5413 { 5414 if (log) 5415 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... " 5416 "Exiting wait loop."); 5417 try_halt_again++; 5418 do_halt = false; 5419 continue; 5420 } 5421 5422 if (!options.GetTryAllThreads()) 5423 { 5424 if (log) 5425 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting."); 5426 return_value = eExpressionInterrupted; 5427 back_to_top = false; 5428 break; 5429 } 5430 5431 if (before_first_timeout) 5432 { 5433 // Set all the other threads to run, and return to the top of the loop, which will continue; 5434 before_first_timeout = false; 5435 thread_plan_sp->SetStopOthers (false); 5436 if (log) 5437 log->PutCString ("Process::RunThreadPlan(): about to resume."); 5438 5439 back_to_top = true; 5440 break; 5441 } 5442 else 5443 { 5444 // Running all threads failed, so return Interrupted. 5445 if (log) 5446 log->PutCString("Process::RunThreadPlan(): running all threads timed out."); 5447 return_value = eExpressionInterrupted; 5448 back_to_top = false; 5449 break; 5450 } 5451 } 5452 } 5453 else 5454 { if (log) 5455 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. " 5456 "I'm getting out of here passing Interrupted."); 5457 return_value = eExpressionInterrupted; 5458 back_to_top = false; 5459 break; 5460 } 5461 } 5462 else 5463 { 5464 try_halt_again++; 5465 continue; 5466 } 5467 } 5468 5469 if (!back_to_top || try_halt_again > num_retries) 5470 break; 5471 else 5472 continue; 5473 } 5474 } // END WAIT LOOP 5475 5476 // If we had to start up a temporary private state thread to run this thread plan, shut it down now. 5477 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread)) 5478 { 5479 StopPrivateStateThread(); 5480 Error error; 5481 m_private_state_thread = backup_private_state_thread; 5482 if (stopper_base_plan_sp) 5483 { 5484 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp); 5485 } 5486 m_public_state.SetValueNoLock(old_state); 5487 5488 } 5489 5490 // Restore the thread state if we are going to discard the plan execution. There are three cases where this 5491 // could happen: 5492 // 1) The execution successfully completed 5493 // 2) We hit a breakpoint, and ignore_breakpoints was true 5494 // 3) We got some other error, and discard_on_error was true 5495 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError()) 5496 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints()); 5497 5498 if (return_value == eExpressionCompleted 5499 || should_unwind) 5500 { 5501 thread_plan_sp->RestoreThreadState(); 5502 } 5503 5504 // Now do some processing on the results of the run: 5505 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint) 5506 { 5507 if (log) 5508 { 5509 StreamString s; 5510 if (event_sp) 5511 event_sp->Dump (&s); 5512 else 5513 { 5514 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL."); 5515 } 5516 5517 StreamString ts; 5518 5519 const char *event_explanation = NULL; 5520 5521 do 5522 { 5523 if (!event_sp) 5524 { 5525 event_explanation = "<no event>"; 5526 break; 5527 } 5528 else if (event_sp->GetType() == eBroadcastBitInterrupt) 5529 { 5530 event_explanation = "<user interrupt>"; 5531 break; 5532 } 5533 else 5534 { 5535 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get()); 5536 5537 if (!event_data) 5538 { 5539 event_explanation = "<no event data>"; 5540 break; 5541 } 5542 5543 Process *process = event_data->GetProcessSP().get(); 5544 5545 if (!process) 5546 { 5547 event_explanation = "<no process>"; 5548 break; 5549 } 5550 5551 ThreadList &thread_list = process->GetThreadList(); 5552 5553 uint32_t num_threads = thread_list.GetSize(); 5554 uint32_t thread_index; 5555 5556 ts.Printf("<%u threads> ", num_threads); 5557 5558 for (thread_index = 0; 5559 thread_index < num_threads; 5560 ++thread_index) 5561 { 5562 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get(); 5563 5564 if (!thread) 5565 { 5566 ts.Printf("<?> "); 5567 continue; 5568 } 5569 5570 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID()); 5571 RegisterContext *register_context = thread->GetRegisterContext().get(); 5572 5573 if (register_context) 5574 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC()); 5575 else 5576 ts.Printf("[ip unknown] "); 5577 5578 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo(); 5579 if (stop_info_sp) 5580 { 5581 const char *stop_desc = stop_info_sp->GetDescription(); 5582 if (stop_desc) 5583 ts.PutCString (stop_desc); 5584 } 5585 ts.Printf(">"); 5586 } 5587 5588 event_explanation = ts.GetData(); 5589 } 5590 } while (0); 5591 5592 if (event_explanation) 5593 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation); 5594 else 5595 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData()); 5596 } 5597 5598 if (should_unwind) 5599 { 5600 if (log) 5601 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", 5602 static_cast<void*>(thread_plan_sp.get())); 5603 thread->DiscardThreadPlansUpToPlan (thread_plan_sp); 5604 thread_plan_sp->SetPrivate (orig_plan_private); 5605 } 5606 else 5607 { 5608 if (log) 5609 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", 5610 static_cast<void*>(thread_plan_sp.get())); 5611 } 5612 } 5613 else if (return_value == eExpressionSetupError) 5614 { 5615 if (log) 5616 log->PutCString("Process::RunThreadPlan(): execution set up error."); 5617 5618 if (options.DoesUnwindOnError()) 5619 { 5620 thread->DiscardThreadPlansUpToPlan (thread_plan_sp); 5621 thread_plan_sp->SetPrivate (orig_plan_private); 5622 } 5623 } 5624 else 5625 { 5626 if (thread->IsThreadPlanDone (thread_plan_sp.get())) 5627 { 5628 if (log) 5629 log->PutCString("Process::RunThreadPlan(): thread plan is done"); 5630 return_value = eExpressionCompleted; 5631 } 5632 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get())) 5633 { 5634 if (log) 5635 log->PutCString("Process::RunThreadPlan(): thread plan was discarded"); 5636 return_value = eExpressionDiscarded; 5637 } 5638 else 5639 { 5640 if (log) 5641 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course"); 5642 if (options.DoesUnwindOnError() && thread_plan_sp) 5643 { 5644 if (log) 5645 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set."); 5646 thread->DiscardThreadPlansUpToPlan (thread_plan_sp); 5647 thread_plan_sp->SetPrivate (orig_plan_private); 5648 } 5649 } 5650 } 5651 5652 // Thread we ran the function in may have gone away because we ran the target 5653 // Check that it's still there, and if it is put it back in the context. Also restore the 5654 // frame in the context if it is still present. 5655 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get(); 5656 if (thread) 5657 { 5658 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id)); 5659 } 5660 5661 // Also restore the current process'es selected frame & thread, since this function calling may 5662 // be done behind the user's back. 5663 5664 if (selected_tid != LLDB_INVALID_THREAD_ID) 5665 { 5666 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid()) 5667 { 5668 // We were able to restore the selected thread, now restore the frame: 5669 Mutex::Locker lock(GetThreadList().GetMutex()); 5670 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id); 5671 if (old_frame_sp) 5672 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get()); 5673 } 5674 } 5675 } 5676 5677 // If the process exited during the run of the thread plan, notify everyone. 5678 5679 if (event_to_broadcast_sp) 5680 { 5681 if (log) 5682 log->PutCString("Process::RunThreadPlan(): rebroadcasting event."); 5683 BroadcastEvent(event_to_broadcast_sp); 5684 } 5685 5686 return return_value; 5687 } 5688 5689 const char * 5690 Process::ExecutionResultAsCString (ExpressionResults result) 5691 { 5692 const char *result_name; 5693 5694 switch (result) 5695 { 5696 case eExpressionCompleted: 5697 result_name = "eExpressionCompleted"; 5698 break; 5699 case eExpressionDiscarded: 5700 result_name = "eExpressionDiscarded"; 5701 break; 5702 case eExpressionInterrupted: 5703 result_name = "eExpressionInterrupted"; 5704 break; 5705 case eExpressionHitBreakpoint: 5706 result_name = "eExpressionHitBreakpoint"; 5707 break; 5708 case eExpressionSetupError: 5709 result_name = "eExpressionSetupError"; 5710 break; 5711 case eExpressionParseError: 5712 result_name = "eExpressionParseError"; 5713 break; 5714 case eExpressionResultUnavailable: 5715 result_name = "eExpressionResultUnavailable"; 5716 break; 5717 case eExpressionTimedOut: 5718 result_name = "eExpressionTimedOut"; 5719 break; 5720 case eExpressionStoppedForDebug: 5721 result_name = "eExpressionStoppedForDebug"; 5722 break; 5723 } 5724 return result_name; 5725 } 5726 5727 void 5728 Process::GetStatus (Stream &strm) 5729 { 5730 const StateType state = GetState(); 5731 if (StateIsStoppedState(state, false)) 5732 { 5733 if (state == eStateExited) 5734 { 5735 int exit_status = GetExitStatus(); 5736 const char *exit_description = GetExitDescription(); 5737 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n", 5738 GetID(), 5739 exit_status, 5740 exit_status, 5741 exit_description ? exit_description : ""); 5742 } 5743 else 5744 { 5745 if (state == eStateConnected) 5746 strm.Printf ("Connected to remote target.\n"); 5747 else 5748 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state)); 5749 } 5750 } 5751 else 5752 { 5753 strm.Printf ("Process %" PRIu64 " is running.\n", GetID()); 5754 } 5755 } 5756 5757 size_t 5758 Process::GetThreadStatus (Stream &strm, 5759 bool only_threads_with_stop_reason, 5760 uint32_t start_frame, 5761 uint32_t num_frames, 5762 uint32_t num_frames_with_source) 5763 { 5764 size_t num_thread_infos_dumped = 0; 5765 5766 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it 5767 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread 5768 // ID's, and look them up one by one: 5769 5770 uint32_t num_threads; 5771 std::vector<uint32_t> thread_index_array; 5772 //Scope for thread list locker; 5773 { 5774 Mutex::Locker locker (GetThreadList().GetMutex()); 5775 ThreadList &curr_thread_list = GetThreadList(); 5776 num_threads = curr_thread_list.GetSize(); 5777 uint32_t idx; 5778 thread_index_array.resize(num_threads); 5779 for (idx = 0; idx < num_threads; ++idx) 5780 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID(); 5781 } 5782 5783 for (uint32_t i = 0; i < num_threads; i++) 5784 { 5785 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_index_array[i])); 5786 if (thread_sp) 5787 { 5788 if (only_threads_with_stop_reason) 5789 { 5790 StopInfoSP stop_info_sp = thread_sp->GetStopInfo(); 5791 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid()) 5792 continue; 5793 } 5794 thread_sp->GetStatus (strm, 5795 start_frame, 5796 num_frames, 5797 num_frames_with_source); 5798 ++num_thread_infos_dumped; 5799 } 5800 else 5801 { 5802 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS)); 5803 if (log) 5804 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus."); 5805 5806 } 5807 } 5808 return num_thread_infos_dumped; 5809 } 5810 5811 void 5812 Process::AddInvalidMemoryRegion (const LoadRange ®ion) 5813 { 5814 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize()); 5815 } 5816 5817 bool 5818 Process::RemoveInvalidMemoryRange (const LoadRange ®ion) 5819 { 5820 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize()); 5821 } 5822 5823 void 5824 Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton) 5825 { 5826 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton)); 5827 } 5828 5829 bool 5830 Process::RunPreResumeActions () 5831 { 5832 bool result = true; 5833 while (!m_pre_resume_actions.empty()) 5834 { 5835 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back(); 5836 m_pre_resume_actions.pop_back(); 5837 bool this_result = action.callback (action.baton); 5838 if (result == true) result = this_result; 5839 } 5840 return result; 5841 } 5842 5843 void 5844 Process::ClearPreResumeActions () 5845 { 5846 m_pre_resume_actions.clear(); 5847 } 5848 5849 void 5850 Process::Flush () 5851 { 5852 m_thread_list.Flush(); 5853 m_extended_thread_list.Flush(); 5854 m_extended_thread_stop_id = 0; 5855 m_queue_list.Clear(); 5856 m_queue_list_stop_id = 0; 5857 } 5858 5859 void 5860 Process::DidExec () 5861 { 5862 Target &target = GetTarget(); 5863 target.CleanupProcess (); 5864 target.ClearModules(false); 5865 m_dynamic_checkers_ap.reset(); 5866 m_abi_sp.reset(); 5867 m_system_runtime_ap.reset(); 5868 m_os_ap.reset(); 5869 m_dyld_ap.reset(); 5870 m_jit_loaders_ap.reset(); 5871 m_image_tokens.clear(); 5872 m_allocated_memory_cache.Clear(); 5873 m_language_runtimes.clear(); 5874 m_thread_list.DiscardThreadPlans(); 5875 m_memory_cache.Clear(true); 5876 DoDidExec(); 5877 CompleteAttach (); 5878 // Flush the process (threads and all stack frames) after running CompleteAttach() 5879 // in case the dynamic loader loaded things in new locations. 5880 Flush(); 5881 5882 // After we figure out what was loaded/unloaded in CompleteAttach, 5883 // we need to let the target know so it can do any cleanup it needs to. 5884 target.DidExec(); 5885 } 5886 5887 addr_t 5888 Process::ResolveIndirectFunction(const Address *address, Error &error) 5889 { 5890 if (address == nullptr) 5891 { 5892 error.SetErrorString("Invalid address argument"); 5893 return LLDB_INVALID_ADDRESS; 5894 } 5895 5896 addr_t function_addr = LLDB_INVALID_ADDRESS; 5897 5898 addr_t addr = address->GetLoadAddress(&GetTarget()); 5899 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr); 5900 if (iter != m_resolved_indirect_addresses.end()) 5901 { 5902 function_addr = (*iter).second; 5903 } 5904 else 5905 { 5906 if (!InferiorCall(this, address, function_addr)) 5907 { 5908 Symbol *symbol = address->CalculateSymbolContextSymbol(); 5909 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s", 5910 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>"); 5911 function_addr = LLDB_INVALID_ADDRESS; 5912 } 5913 else 5914 { 5915 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr)); 5916 } 5917 } 5918 return function_addr; 5919 } 5920 5921 void 5922 Process::ModulesDidLoad (ModuleList &module_list) 5923 { 5924 SystemRuntime *sys_runtime = GetSystemRuntime(); 5925 if (sys_runtime) 5926 { 5927 sys_runtime->ModulesDidLoad (module_list); 5928 } 5929 5930 GetJITLoaders().ModulesDidLoad (module_list); 5931 } 5932