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