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