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