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