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