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 12 #include "lldb/lldb-private-log.h" 13 14 #include "lldb/Breakpoint/StoppointCallbackContext.h" 15 #include "lldb/Breakpoint/BreakpointLocation.h" 16 #include "lldb/Core/Event.h" 17 #include "lldb/Core/ConnectionFileDescriptor.h" 18 #include "lldb/Core/Debugger.h" 19 #include "lldb/Core/InputReader.h" 20 #include "lldb/Core/Log.h" 21 #include "lldb/Core/PluginManager.h" 22 #include "lldb/Core/State.h" 23 #include "lldb/Interpreter/CommandInterpreter.h" 24 #include "lldb/Host/Host.h" 25 #include "lldb/Target/ABI.h" 26 #include "lldb/Target/DynamicLoader.h" 27 #include "lldb/Target/LanguageRuntime.h" 28 #include "lldb/Target/CPPLanguageRuntime.h" 29 #include "lldb/Target/ObjCLanguageRuntime.h" 30 #include "lldb/Target/RegisterContext.h" 31 #include "lldb/Target/StopInfo.h" 32 #include "lldb/Target/Target.h" 33 #include "lldb/Target/TargetList.h" 34 #include "lldb/Target/Thread.h" 35 #include "lldb/Target/ThreadPlan.h" 36 37 using namespace lldb; 38 using namespace lldb_private; 39 40 41 //---------------------------------------------------------------------- 42 // MemoryCache constructor 43 //---------------------------------------------------------------------- 44 Process::MemoryCache::MemoryCache() : 45 m_cache_line_byte_size (512), 46 m_cache_mutex (Mutex::eMutexTypeRecursive), 47 m_cache () 48 { 49 } 50 51 //---------------------------------------------------------------------- 52 // Destructor 53 //---------------------------------------------------------------------- 54 Process::MemoryCache::~MemoryCache() 55 { 56 } 57 58 void 59 Process::MemoryCache::Clear() 60 { 61 Mutex::Locker locker (m_cache_mutex); 62 m_cache.clear(); 63 } 64 65 void 66 Process::MemoryCache::Flush (addr_t addr, size_t size) 67 { 68 if (size == 0) 69 return; 70 71 const uint32_t cache_line_byte_size = m_cache_line_byte_size; 72 const addr_t end_addr = (addr + size - 1); 73 const addr_t flush_start_addr = addr - (addr % cache_line_byte_size); 74 const addr_t flush_end_addr = end_addr - (end_addr % cache_line_byte_size); 75 76 Mutex::Locker locker (m_cache_mutex); 77 if (m_cache.empty()) 78 return; 79 80 assert ((flush_start_addr % cache_line_byte_size) == 0); 81 82 for (addr_t curr_addr = flush_start_addr; curr_addr <= flush_end_addr; curr_addr += cache_line_byte_size) 83 { 84 collection::iterator pos = m_cache.find (curr_addr); 85 if (pos != m_cache.end()) 86 m_cache.erase(pos); 87 } 88 } 89 90 size_t 91 Process::MemoryCache::Read 92 ( 93 Process *process, 94 addr_t addr, 95 void *dst, 96 size_t dst_len, 97 Error &error 98 ) 99 { 100 size_t bytes_left = dst_len; 101 if (dst && bytes_left > 0) 102 { 103 const uint32_t cache_line_byte_size = m_cache_line_byte_size; 104 uint8_t *dst_buf = (uint8_t *)dst; 105 addr_t curr_addr = addr - (addr % cache_line_byte_size); 106 addr_t cache_offset = addr - curr_addr; 107 Mutex::Locker locker (m_cache_mutex); 108 109 while (bytes_left > 0) 110 { 111 collection::const_iterator pos = m_cache.find (curr_addr); 112 collection::const_iterator end = m_cache.end (); 113 114 if (pos != end) 115 { 116 size_t curr_read_size = cache_line_byte_size - cache_offset; 117 if (curr_read_size > bytes_left) 118 curr_read_size = bytes_left; 119 120 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes() + cache_offset, curr_read_size); 121 122 bytes_left -= curr_read_size; 123 curr_addr += curr_read_size + cache_offset; 124 cache_offset = 0; 125 126 if (bytes_left > 0) 127 { 128 // Get sequential cache page hits 129 for (++pos; (pos != end) && (bytes_left > 0); ++pos) 130 { 131 assert ((curr_addr % cache_line_byte_size) == 0); 132 133 if (pos->first != curr_addr) 134 break; 135 136 curr_read_size = pos->second->GetByteSize(); 137 if (curr_read_size > bytes_left) 138 curr_read_size = bytes_left; 139 140 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes(), curr_read_size); 141 142 bytes_left -= curr_read_size; 143 curr_addr += curr_read_size; 144 145 // We have a cache page that succeeded to read some bytes 146 // but not an entire page. If this happens, we must cap 147 // off how much data we are able to read... 148 if (pos->second->GetByteSize() != cache_line_byte_size) 149 return dst_len - bytes_left; 150 } 151 } 152 } 153 154 // We need to read from the process 155 156 if (bytes_left > 0) 157 { 158 assert ((curr_addr % cache_line_byte_size) == 0); 159 std::auto_ptr<DataBufferHeap> data_buffer_heap_ap(new DataBufferHeap (cache_line_byte_size, 0)); 160 size_t process_bytes_read = process->ReadMemoryFromInferior (curr_addr, 161 data_buffer_heap_ap->GetBytes(), 162 data_buffer_heap_ap->GetByteSize(), 163 error); 164 if (process_bytes_read == 0) 165 return dst_len - bytes_left; 166 167 if (process_bytes_read != cache_line_byte_size) 168 data_buffer_heap_ap->SetByteSize (process_bytes_read); 169 m_cache[curr_addr] = DataBufferSP (data_buffer_heap_ap.release()); 170 // We have read data and put it into the cache, continue through the 171 // loop again to get the data out of the cache... 172 } 173 } 174 } 175 176 return dst_len - bytes_left; 177 } 178 179 Process* 180 Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener) 181 { 182 ProcessCreateInstance create_callback = NULL; 183 if (plugin_name) 184 { 185 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name); 186 if (create_callback) 187 { 188 std::auto_ptr<Process> debugger_ap(create_callback(target, listener)); 189 if (debugger_ap->CanDebug(target)) 190 return debugger_ap.release(); 191 } 192 } 193 else 194 { 195 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx) 196 { 197 std::auto_ptr<Process> debugger_ap(create_callback(target, listener)); 198 if (debugger_ap->CanDebug(target)) 199 return debugger_ap.release(); 200 } 201 } 202 return NULL; 203 } 204 205 206 //---------------------------------------------------------------------- 207 // Process constructor 208 //---------------------------------------------------------------------- 209 Process::Process(Target &target, Listener &listener) : 210 UserID (LLDB_INVALID_PROCESS_ID), 211 Broadcaster ("lldb.process"), 212 ProcessInstanceSettings (*GetSettingsController()), 213 m_target (target), 214 m_public_state (eStateUnloaded), 215 m_private_state (eStateUnloaded), 216 m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"), 217 m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"), 218 m_private_state_listener ("lldb.process.internal_state_listener"), 219 m_private_state_control_wait(), 220 m_private_state_thread (LLDB_INVALID_HOST_THREAD), 221 m_stop_id (0), 222 m_thread_index_id (0), 223 m_exit_status (-1), 224 m_exit_string (), 225 m_thread_list (this), 226 m_notifications (), 227 m_image_tokens (), 228 m_listener (listener), 229 m_breakpoint_site_list (), 230 m_dynamic_checkers_ap (), 231 m_unix_signals (), 232 m_target_triple (), 233 m_byte_order (eByteOrderHost), 234 m_addr_byte_size (0), 235 m_abi_sp (), 236 m_process_input_reader (), 237 m_stdio_communication ("process.stdio"), 238 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive), 239 m_stdout_data (), 240 m_memory_cache () 241 { 242 UpdateInstanceName(); 243 244 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); 245 if (log) 246 log->Printf ("%p Process::Process()", this); 247 248 SetEventName (eBroadcastBitStateChanged, "state-changed"); 249 SetEventName (eBroadcastBitInterrupt, "interrupt"); 250 SetEventName (eBroadcastBitSTDOUT, "stdout-available"); 251 SetEventName (eBroadcastBitSTDERR, "stderr-available"); 252 253 listener.StartListeningForEvents (this, 254 eBroadcastBitStateChanged | 255 eBroadcastBitInterrupt | 256 eBroadcastBitSTDOUT | 257 eBroadcastBitSTDERR); 258 259 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster, 260 eBroadcastBitStateChanged); 261 262 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster, 263 eBroadcastInternalStateControlStop | 264 eBroadcastInternalStateControlPause | 265 eBroadcastInternalStateControlResume); 266 } 267 268 //---------------------------------------------------------------------- 269 // Destructor 270 //---------------------------------------------------------------------- 271 Process::~Process() 272 { 273 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); 274 if (log) 275 log->Printf ("%p Process::~Process()", this); 276 StopPrivateStateThread(); 277 } 278 279 void 280 Process::Finalize() 281 { 282 // Do any cleanup needed prior to being destructed... Subclasses 283 // that override this method should call this superclass method as well. 284 } 285 286 void 287 Process::RegisterNotificationCallbacks (const Notifications& callbacks) 288 { 289 m_notifications.push_back(callbacks); 290 if (callbacks.initialize != NULL) 291 callbacks.initialize (callbacks.baton, this); 292 } 293 294 bool 295 Process::UnregisterNotificationCallbacks(const Notifications& callbacks) 296 { 297 std::vector<Notifications>::iterator pos, end = m_notifications.end(); 298 for (pos = m_notifications.begin(); pos != end; ++pos) 299 { 300 if (pos->baton == callbacks.baton && 301 pos->initialize == callbacks.initialize && 302 pos->process_state_changed == callbacks.process_state_changed) 303 { 304 m_notifications.erase(pos); 305 return true; 306 } 307 } 308 return false; 309 } 310 311 void 312 Process::SynchronouslyNotifyStateChanged (StateType state) 313 { 314 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end(); 315 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos) 316 { 317 if (notification_pos->process_state_changed) 318 notification_pos->process_state_changed (notification_pos->baton, this, state); 319 } 320 } 321 322 // FIXME: We need to do some work on events before the general Listener sees them. 323 // For instance if we are continuing from a breakpoint, we need to ensure that we do 324 // the little "insert real insn, step & stop" trick. But we can't do that when the 325 // event is delivered by the broadcaster - since that is done on the thread that is 326 // waiting for new events, so if we needed more than one event for our handling, we would 327 // stall. So instead we do it when we fetch the event off of the queue. 328 // 329 330 StateType 331 Process::GetNextEvent (EventSP &event_sp) 332 { 333 StateType state = eStateInvalid; 334 335 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp) 336 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get()); 337 338 return state; 339 } 340 341 342 StateType 343 Process::WaitForProcessToStop (const TimeValue *timeout) 344 { 345 StateType match_states[] = { eStateStopped, eStateCrashed, eStateDetached, eStateExited, eStateUnloaded }; 346 return WaitForState (timeout, match_states, sizeof(match_states) / sizeof(StateType)); 347 } 348 349 350 StateType 351 Process::WaitForState 352 ( 353 const TimeValue *timeout, 354 const StateType *match_states, const uint32_t num_match_states 355 ) 356 { 357 EventSP event_sp; 358 uint32_t i; 359 StateType state = GetState(); 360 while (state != eStateInvalid) 361 { 362 // If we are exited or detached, we won't ever get back to any 363 // other valid state... 364 if (state == eStateDetached || state == eStateExited) 365 return state; 366 367 state = WaitForStateChangedEvents (timeout, event_sp); 368 369 for (i=0; i<num_match_states; ++i) 370 { 371 if (match_states[i] == state) 372 return state; 373 } 374 } 375 return state; 376 } 377 378 bool 379 Process::HijackProcessEvents (Listener *listener) 380 { 381 if (listener != NULL) 382 { 383 return HijackBroadcaster(listener, eBroadcastBitStateChanged); 384 } 385 else 386 return false; 387 } 388 389 void 390 Process::RestoreProcessEvents () 391 { 392 RestoreBroadcaster(); 393 } 394 395 StateType 396 Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp) 397 { 398 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 399 400 if (log) 401 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout); 402 403 StateType state = eStateInvalid; 404 if (m_listener.WaitForEventForBroadcasterWithType (timeout, 405 this, 406 eBroadcastBitStateChanged, 407 event_sp)) 408 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 409 410 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS); 411 if (log) 412 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", 413 __FUNCTION__, 414 timeout, 415 StateAsCString(state)); 416 return state; 417 } 418 419 Event * 420 Process::PeekAtStateChangedEvents () 421 { 422 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 423 424 if (log) 425 log->Printf ("Process::%s...", __FUNCTION__); 426 427 Event *event_ptr; 428 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this, 429 eBroadcastBitStateChanged); 430 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS); 431 if (log) 432 { 433 if (event_ptr) 434 { 435 log->Printf ("Process::%s (event_ptr) => %s", 436 __FUNCTION__, 437 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr))); 438 } 439 else 440 { 441 log->Printf ("Process::%s no events found", 442 __FUNCTION__); 443 } 444 } 445 return event_ptr; 446 } 447 448 StateType 449 Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp) 450 { 451 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 452 453 if (log) 454 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout); 455 456 StateType state = eStateInvalid; 457 if (m_private_state_listener.WaitForEventForBroadcasterWithType(timeout, 458 &m_private_state_broadcaster, 459 eBroadcastBitStateChanged, 460 event_sp)) 461 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 462 463 // This is a bit of a hack, but when we wait here we could very well return 464 // to the command-line, and that could disable the log, which would render the 465 // log we got above invalid. 466 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS); 467 if (log) 468 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state)); 469 return state; 470 } 471 472 bool 473 Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only) 474 { 475 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 476 477 if (log) 478 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout); 479 480 if (control_only) 481 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp); 482 else 483 return m_private_state_listener.WaitForEvent(timeout, event_sp); 484 } 485 486 bool 487 Process::IsRunning () const 488 { 489 return StateIsRunningState (m_public_state.GetValue()); 490 } 491 492 int 493 Process::GetExitStatus () 494 { 495 if (m_public_state.GetValue() == eStateExited) 496 return m_exit_status; 497 return -1; 498 } 499 500 501 void 502 Process::ProcessInstanceSettings::GetHostEnvironmentIfNeeded () 503 { 504 if (m_inherit_host_env && !m_got_host_env) 505 { 506 m_got_host_env = true; 507 StringList host_env; 508 const size_t host_env_count = Host::GetEnvironment (host_env); 509 for (size_t idx=0; idx<host_env_count; idx++) 510 { 511 const char *env_entry = host_env.GetStringAtIndex (idx); 512 if (env_entry) 513 { 514 const char *equal_pos = ::strchr(env_entry, '='); 515 if (equal_pos) 516 { 517 std::string key (env_entry, equal_pos - env_entry); 518 std::string value (equal_pos + 1); 519 if (m_env_vars.find (key) == m_env_vars.end()) 520 m_env_vars[key] = value; 521 } 522 } 523 } 524 } 525 } 526 527 528 size_t 529 Process::ProcessInstanceSettings::GetEnvironmentAsArgs (Args &env) 530 { 531 GetHostEnvironmentIfNeeded (); 532 533 dictionary::const_iterator pos, end = m_env_vars.end(); 534 for (pos = m_env_vars.begin(); pos != end; ++pos) 535 { 536 std::string env_var_equal_value (pos->first); 537 env_var_equal_value.append(1, '='); 538 env_var_equal_value.append (pos->second); 539 env.AppendArgument (env_var_equal_value.c_str()); 540 } 541 return env.GetArgumentCount(); 542 } 543 544 545 const char * 546 Process::GetExitDescription () 547 { 548 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty()) 549 return m_exit_string.c_str(); 550 return NULL; 551 } 552 553 void 554 Process::SetExitStatus (int status, const char *cstr) 555 { 556 if (m_private_state.GetValue() != eStateExited) 557 { 558 m_exit_status = status; 559 if (cstr) 560 m_exit_string = cstr; 561 else 562 m_exit_string.clear(); 563 564 DidExit (); 565 566 SetPrivateState (eStateExited); 567 } 568 } 569 570 // This static callback can be used to watch for local child processes on 571 // the current host. The the child process exits, the process will be 572 // found in the global target list (we want to be completely sure that the 573 // lldb_private::Process doesn't go away before we can deliver the signal. 574 bool 575 Process::SetProcessExitStatus 576 ( 577 void *callback_baton, 578 lldb::pid_t pid, 579 int signo, // Zero for no signal 580 int exit_status // Exit value of process if signal is zero 581 ) 582 { 583 if (signo == 0 || exit_status) 584 { 585 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid)); 586 if (target_sp) 587 { 588 ProcessSP process_sp (target_sp->GetProcessSP()); 589 if (process_sp) 590 { 591 const char *signal_cstr = NULL; 592 if (signo) 593 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo); 594 595 process_sp->SetExitStatus (exit_status, signal_cstr); 596 } 597 } 598 return true; 599 } 600 return false; 601 } 602 603 604 uint32_t 605 Process::GetNextThreadIndexID () 606 { 607 return ++m_thread_index_id; 608 } 609 610 StateType 611 Process::GetState() 612 { 613 // If any other threads access this we will need a mutex for it 614 return m_public_state.GetValue (); 615 } 616 617 void 618 Process::SetPublicState (StateType new_state) 619 { 620 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE)); 621 if (log) 622 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state)); 623 m_public_state.SetValue (new_state); 624 } 625 626 StateType 627 Process::GetPrivateState () 628 { 629 return m_private_state.GetValue(); 630 } 631 632 void 633 Process::SetPrivateState (StateType new_state) 634 { 635 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE)); 636 bool state_changed = false; 637 638 if (log) 639 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state)); 640 641 Mutex::Locker locker(m_private_state.GetMutex()); 642 643 const StateType old_state = m_private_state.GetValueNoLock (); 644 state_changed = old_state != new_state; 645 if (state_changed) 646 { 647 m_private_state.SetValueNoLock (new_state); 648 if (StateIsStoppedState(new_state)) 649 { 650 m_stop_id++; 651 m_memory_cache.Clear(); 652 if (log) 653 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id); 654 } 655 // Use our target to get a shared pointer to ourselves... 656 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state)); 657 } 658 else 659 { 660 if (log) 661 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state)); 662 } 663 } 664 665 666 uint32_t 667 Process::GetStopID() const 668 { 669 return m_stop_id; 670 } 671 672 addr_t 673 Process::GetImageInfoAddress() 674 { 675 return LLDB_INVALID_ADDRESS; 676 } 677 678 //---------------------------------------------------------------------- 679 // LoadImage 680 // 681 // This function provides a default implementation that works for most 682 // unix variants. Any Process subclasses that need to do shared library 683 // loading differently should override LoadImage and UnloadImage and 684 // do what is needed. 685 //---------------------------------------------------------------------- 686 uint32_t 687 Process::LoadImage (const FileSpec &image_spec, Error &error) 688 { 689 DynamicLoader *loader = GetDynamicLoader(); 690 if (loader) 691 { 692 error = loader->CanLoadImage(); 693 if (error.Fail()) 694 return LLDB_INVALID_IMAGE_TOKEN; 695 } 696 697 if (error.Success()) 698 { 699 ThreadSP thread_sp(GetThreadList ().GetSelectedThread()); 700 if (thread_sp == NULL) 701 thread_sp = GetThreadList ().GetThreadAtIndex(0, true); 702 703 if (thread_sp) 704 { 705 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0)); 706 707 if (frame_sp) 708 { 709 ExecutionContext exe_ctx; 710 frame_sp->CalculateExecutionContext (exe_ctx); 711 bool unwind_on_error = true; 712 StreamString expr; 713 char path[PATH_MAX]; 714 image_spec.GetPath(path, sizeof(path)); 715 expr.Printf("dlopen (\"%s\", 2)", path); 716 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n"; 717 lldb::ValueObjectSP result_valobj_sp; 718 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, expr.GetData(), prefix, result_valobj_sp); 719 if (result_valobj_sp->GetError().Success()) 720 { 721 Scalar scalar; 722 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar)) 723 { 724 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS); 725 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS) 726 { 727 uint32_t image_token = m_image_tokens.size(); 728 m_image_tokens.push_back (image_ptr); 729 return image_token; 730 } 731 } 732 } 733 } 734 } 735 } 736 return LLDB_INVALID_IMAGE_TOKEN; 737 } 738 739 //---------------------------------------------------------------------- 740 // UnloadImage 741 // 742 // This function provides a default implementation that works for most 743 // unix variants. Any Process subclasses that need to do shared library 744 // loading differently should override LoadImage and UnloadImage and 745 // do what is needed. 746 //---------------------------------------------------------------------- 747 Error 748 Process::UnloadImage (uint32_t image_token) 749 { 750 Error error; 751 if (image_token < m_image_tokens.size()) 752 { 753 const addr_t image_addr = m_image_tokens[image_token]; 754 if (image_addr == LLDB_INVALID_ADDRESS) 755 { 756 error.SetErrorString("image already unloaded"); 757 } 758 else 759 { 760 DynamicLoader *loader = GetDynamicLoader(); 761 if (loader) 762 error = loader->CanLoadImage(); 763 764 if (error.Success()) 765 { 766 ThreadSP thread_sp(GetThreadList ().GetSelectedThread()); 767 if (thread_sp == NULL) 768 thread_sp = GetThreadList ().GetThreadAtIndex(0, true); 769 770 if (thread_sp) 771 { 772 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0)); 773 774 if (frame_sp) 775 { 776 ExecutionContext exe_ctx; 777 frame_sp->CalculateExecutionContext (exe_ctx); 778 bool unwind_on_error = true; 779 StreamString expr; 780 expr.Printf("dlclose ((void *)0x%llx)", image_addr); 781 const char *prefix = "extern \"C\" int dlclose(void* handle);\n"; 782 lldb::ValueObjectSP result_valobj_sp; 783 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, expr.GetData(), prefix, result_valobj_sp); 784 if (result_valobj_sp->GetError().Success()) 785 { 786 Scalar scalar; 787 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar)) 788 { 789 if (scalar.UInt(1)) 790 { 791 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData()); 792 } 793 else 794 { 795 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS; 796 } 797 } 798 } 799 else 800 { 801 error = result_valobj_sp->GetError(); 802 } 803 } 804 } 805 } 806 } 807 } 808 else 809 { 810 error.SetErrorString("invalid image token"); 811 } 812 return error; 813 } 814 815 DynamicLoader * 816 Process::GetDynamicLoader() 817 { 818 return NULL; 819 } 820 821 const ABI * 822 Process::GetABI() 823 { 824 ConstString& triple = m_target_triple; 825 826 if (triple.IsEmpty()) 827 return NULL; 828 829 if (m_abi_sp.get() == NULL) 830 { 831 m_abi_sp.reset(ABI::FindPlugin(triple)); 832 } 833 834 return m_abi_sp.get(); 835 } 836 837 LanguageRuntime * 838 Process::GetLanguageRuntime(lldb::LanguageType language) 839 { 840 LanguageRuntimeCollection::iterator pos; 841 pos = m_language_runtimes.find (language); 842 if (pos == m_language_runtimes.end()) 843 { 844 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language)); 845 846 m_language_runtimes[language] 847 = runtime; 848 return runtime.get(); 849 } 850 else 851 return (*pos).second.get(); 852 } 853 854 CPPLanguageRuntime * 855 Process::GetCPPLanguageRuntime () 856 { 857 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus); 858 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus) 859 return static_cast<CPPLanguageRuntime *> (runtime); 860 return NULL; 861 } 862 863 ObjCLanguageRuntime * 864 Process::GetObjCLanguageRuntime () 865 { 866 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC); 867 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC) 868 return static_cast<ObjCLanguageRuntime *> (runtime); 869 return NULL; 870 } 871 872 BreakpointSiteList & 873 Process::GetBreakpointSiteList() 874 { 875 return m_breakpoint_site_list; 876 } 877 878 const BreakpointSiteList & 879 Process::GetBreakpointSiteList() const 880 { 881 return m_breakpoint_site_list; 882 } 883 884 885 void 886 Process::DisableAllBreakpointSites () 887 { 888 m_breakpoint_site_list.SetEnabledForAll (false); 889 } 890 891 Error 892 Process::ClearBreakpointSiteByID (lldb::user_id_t break_id) 893 { 894 Error error (DisableBreakpointSiteByID (break_id)); 895 896 if (error.Success()) 897 m_breakpoint_site_list.Remove(break_id); 898 899 return error; 900 } 901 902 Error 903 Process::DisableBreakpointSiteByID (lldb::user_id_t break_id) 904 { 905 Error error; 906 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id); 907 if (bp_site_sp) 908 { 909 if (bp_site_sp->IsEnabled()) 910 error = DisableBreakpoint (bp_site_sp.get()); 911 } 912 else 913 { 914 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id); 915 } 916 917 return error; 918 } 919 920 Error 921 Process::EnableBreakpointSiteByID (lldb::user_id_t break_id) 922 { 923 Error error; 924 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id); 925 if (bp_site_sp) 926 { 927 if (!bp_site_sp->IsEnabled()) 928 error = EnableBreakpoint (bp_site_sp.get()); 929 } 930 else 931 { 932 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id); 933 } 934 return error; 935 } 936 937 lldb::break_id_t 938 Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware) 939 { 940 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target); 941 if (load_addr != LLDB_INVALID_ADDRESS) 942 { 943 BreakpointSiteSP bp_site_sp; 944 945 // Look up this breakpoint site. If it exists, then add this new owner, otherwise 946 // create a new breakpoint site and add it. 947 948 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr); 949 950 if (bp_site_sp) 951 { 952 bp_site_sp->AddOwner (owner); 953 owner->SetBreakpointSite (bp_site_sp); 954 return bp_site_sp->GetID(); 955 } 956 else 957 { 958 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware)); 959 if (bp_site_sp) 960 { 961 if (EnableBreakpoint (bp_site_sp.get()).Success()) 962 { 963 owner->SetBreakpointSite (bp_site_sp); 964 return m_breakpoint_site_list.Add (bp_site_sp); 965 } 966 } 967 } 968 } 969 // We failed to enable the breakpoint 970 return LLDB_INVALID_BREAK_ID; 971 972 } 973 974 void 975 Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp) 976 { 977 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id); 978 if (num_owners == 0) 979 { 980 DisableBreakpoint(bp_site_sp.get()); 981 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress()); 982 } 983 } 984 985 986 size_t 987 Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const 988 { 989 size_t bytes_removed = 0; 990 addr_t intersect_addr; 991 size_t intersect_size; 992 size_t opcode_offset; 993 size_t idx; 994 BreakpointSiteSP bp; 995 996 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx) 997 { 998 if (bp->GetType() == BreakpointSite::eSoftware) 999 { 1000 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset)) 1001 { 1002 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size); 1003 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size); 1004 assert(opcode_offset + intersect_size <= bp->GetByteSize()); 1005 size_t buf_offset = intersect_addr - bp_addr; 1006 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size); 1007 } 1008 } 1009 } 1010 return bytes_removed; 1011 } 1012 1013 1014 Error 1015 Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site) 1016 { 1017 Error error; 1018 assert (bp_site != NULL); 1019 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 1020 const addr_t bp_addr = bp_site->GetLoadAddress(); 1021 if (log) 1022 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr); 1023 if (bp_site->IsEnabled()) 1024 { 1025 if (log) 1026 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr); 1027 return error; 1028 } 1029 1030 if (bp_addr == LLDB_INVALID_ADDRESS) 1031 { 1032 error.SetErrorString("BreakpointSite contains an invalid load address."); 1033 return error; 1034 } 1035 // Ask the lldb::Process subclass to fill in the correct software breakpoint 1036 // trap for the breakpoint site 1037 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site); 1038 1039 if (bp_opcode_size == 0) 1040 { 1041 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr); 1042 } 1043 else 1044 { 1045 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes(); 1046 1047 if (bp_opcode_bytes == NULL) 1048 { 1049 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode."); 1050 return error; 1051 } 1052 1053 // Save the original opcode by reading it 1054 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size) 1055 { 1056 // Write a software breakpoint in place of the original opcode 1057 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size) 1058 { 1059 uint8_t verify_bp_opcode_bytes[64]; 1060 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size) 1061 { 1062 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0) 1063 { 1064 bp_site->SetEnabled(true); 1065 bp_site->SetType (BreakpointSite::eSoftware); 1066 if (log) 1067 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", 1068 bp_site->GetID(), 1069 (uint64_t)bp_addr); 1070 } 1071 else 1072 error.SetErrorString("Failed to verify the breakpoint trap in memory."); 1073 } 1074 else 1075 error.SetErrorString("Unable to read memory to verify breakpoint trap."); 1076 } 1077 else 1078 error.SetErrorString("Unable to write breakpoint trap to memory."); 1079 } 1080 else 1081 error.SetErrorString("Unable to read memory at breakpoint address."); 1082 } 1083 if (log) 1084 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s", 1085 bp_site->GetID(), 1086 (uint64_t)bp_addr, 1087 error.AsCString()); 1088 return error; 1089 } 1090 1091 Error 1092 Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site) 1093 { 1094 Error error; 1095 assert (bp_site != NULL); 1096 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 1097 addr_t bp_addr = bp_site->GetLoadAddress(); 1098 lldb::user_id_t breakID = bp_site->GetID(); 1099 if (log) 1100 log->Printf ("ProcessMacOSX::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr); 1101 1102 if (bp_site->IsHardware()) 1103 { 1104 error.SetErrorString("Breakpoint site is a hardware breakpoint."); 1105 } 1106 else if (bp_site->IsEnabled()) 1107 { 1108 const size_t break_op_size = bp_site->GetByteSize(); 1109 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes(); 1110 if (break_op_size > 0) 1111 { 1112 // Clear a software breakoint instruction 1113 uint8_t curr_break_op[8]; 1114 assert (break_op_size <= sizeof(curr_break_op)); 1115 bool break_op_found = false; 1116 1117 // Read the breakpoint opcode 1118 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size) 1119 { 1120 bool verify = false; 1121 // Make sure we have the a breakpoint opcode exists at this address 1122 if (::memcmp (curr_break_op, break_op, break_op_size) == 0) 1123 { 1124 break_op_found = true; 1125 // We found a valid breakpoint opcode at this address, now restore 1126 // the saved opcode. 1127 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size) 1128 { 1129 verify = true; 1130 } 1131 else 1132 error.SetErrorString("Memory write failed when restoring original opcode."); 1133 } 1134 else 1135 { 1136 error.SetErrorString("Original breakpoint trap is no longer in memory."); 1137 // Set verify to true and so we can check if the original opcode has already been restored 1138 verify = true; 1139 } 1140 1141 if (verify) 1142 { 1143 uint8_t verify_opcode[8]; 1144 assert (break_op_size < sizeof(verify_opcode)); 1145 // Verify that our original opcode made it back to the inferior 1146 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size) 1147 { 1148 // compare the memory we just read with the original opcode 1149 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0) 1150 { 1151 // SUCCESS 1152 bp_site->SetEnabled(false); 1153 if (log) 1154 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr); 1155 return error; 1156 } 1157 else 1158 { 1159 if (break_op_found) 1160 error.SetErrorString("Failed to restore original opcode."); 1161 } 1162 } 1163 else 1164 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored."); 1165 } 1166 } 1167 else 1168 error.SetErrorString("Unable to read memory that should contain the breakpoint trap."); 1169 } 1170 } 1171 else 1172 { 1173 if (log) 1174 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr); 1175 return error; 1176 } 1177 1178 if (log) 1179 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s", 1180 bp_site->GetID(), 1181 (uint64_t)bp_addr, 1182 error.AsCString()); 1183 return error; 1184 1185 } 1186 1187 // Comment out line below to disable memory caching 1188 #define ENABLE_MEMORY_CACHING 1189 // Uncomment to verify memory caching works after making changes to caching code 1190 //#define VERIFY_MEMORY_READS 1191 1192 #if defined (ENABLE_MEMORY_CACHING) 1193 1194 #if defined (VERIFY_MEMORY_READS) 1195 1196 size_t 1197 Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error) 1198 { 1199 // Memory caching is enabled, with debug verification 1200 if (buf && size) 1201 { 1202 // Uncomment the line below to make sure memory caching is working. 1203 // I ran this through the test suite and got no assertions, so I am 1204 // pretty confident this is working well. If any changes are made to 1205 // memory caching, uncomment the line below and test your changes! 1206 1207 // Verify all memory reads by using the cache first, then redundantly 1208 // reading the same memory from the inferior and comparing to make sure 1209 // everything is exactly the same. 1210 std::string verify_buf (size, '\0'); 1211 assert (verify_buf.size() == size); 1212 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error); 1213 Error verify_error; 1214 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error); 1215 assert (cache_bytes_read == verify_bytes_read); 1216 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0); 1217 assert (verify_error.Success() == error.Success()); 1218 return cache_bytes_read; 1219 } 1220 return 0; 1221 } 1222 1223 #else // #if defined (VERIFY_MEMORY_READS) 1224 1225 size_t 1226 Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error) 1227 { 1228 // Memory caching enabled, no verification 1229 return m_memory_cache.Read (this, addr, buf, size, error); 1230 } 1231 1232 #endif // #else for #if defined (VERIFY_MEMORY_READS) 1233 1234 #else // #if defined (ENABLE_MEMORY_CACHING) 1235 1236 size_t 1237 Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error) 1238 { 1239 // Memory caching is disabled 1240 return ReadMemoryFromInferior (addr, buf, size, error); 1241 } 1242 1243 #endif // #else for #if defined (ENABLE_MEMORY_CACHING) 1244 1245 1246 size_t 1247 Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error) 1248 { 1249 if (buf == NULL || size == 0) 1250 return 0; 1251 1252 size_t bytes_read = 0; 1253 uint8_t *bytes = (uint8_t *)buf; 1254 1255 while (bytes_read < size) 1256 { 1257 const size_t curr_size = size - bytes_read; 1258 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read, 1259 bytes + bytes_read, 1260 curr_size, 1261 error); 1262 bytes_read += curr_bytes_read; 1263 if (curr_bytes_read == curr_size || curr_bytes_read == 0) 1264 break; 1265 } 1266 1267 // Replace any software breakpoint opcodes that fall into this range back 1268 // into "buf" before we return 1269 if (bytes_read > 0) 1270 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf); 1271 return bytes_read; 1272 } 1273 1274 uint64_t 1275 Process::ReadUnsignedInteger (lldb::addr_t vm_addr, size_t integer_byte_size, Error &error) 1276 { 1277 if (integer_byte_size > sizeof(uint64_t)) 1278 { 1279 error.SetErrorString ("unsupported integer size"); 1280 } 1281 else 1282 { 1283 uint8_t tmp[sizeof(uint64_t)]; 1284 DataExtractor data (tmp, integer_byte_size, GetByteOrder(), GetAddressByteSize()); 1285 if (ReadMemory (vm_addr, tmp, integer_byte_size, error) == integer_byte_size) 1286 { 1287 uint32_t offset = 0; 1288 return data.GetMaxU64 (&offset, integer_byte_size); 1289 } 1290 } 1291 // Any plug-in that doesn't return success a memory read with the number 1292 // of bytes that were requested should be setting the error 1293 assert (error.Fail()); 1294 return 0; 1295 } 1296 1297 size_t 1298 Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error) 1299 { 1300 size_t bytes_written = 0; 1301 const uint8_t *bytes = (const uint8_t *)buf; 1302 1303 while (bytes_written < size) 1304 { 1305 const size_t curr_size = size - bytes_written; 1306 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written, 1307 bytes + bytes_written, 1308 curr_size, 1309 error); 1310 bytes_written += curr_bytes_written; 1311 if (curr_bytes_written == curr_size || curr_bytes_written == 0) 1312 break; 1313 } 1314 return bytes_written; 1315 } 1316 1317 size_t 1318 Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error) 1319 { 1320 #if defined (ENABLE_MEMORY_CACHING) 1321 m_memory_cache.Flush (addr, size); 1322 #endif 1323 1324 if (buf == NULL || size == 0) 1325 return 0; 1326 // We need to write any data that would go where any current software traps 1327 // (enabled software breakpoints) any software traps (breakpoints) that we 1328 // may have placed in our tasks memory. 1329 1330 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr); 1331 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end(); 1332 1333 if (iter == end || iter->second->GetLoadAddress() > addr + size) 1334 return DoWriteMemory(addr, buf, size, error); 1335 1336 BreakpointSiteList::collection::const_iterator pos; 1337 size_t bytes_written = 0; 1338 addr_t intersect_addr = 0; 1339 size_t intersect_size = 0; 1340 size_t opcode_offset = 0; 1341 const uint8_t *ubuf = (const uint8_t *)buf; 1342 1343 for (pos = iter; pos != end; ++pos) 1344 { 1345 BreakpointSiteSP bp; 1346 bp = pos->second; 1347 1348 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset)); 1349 assert(addr <= intersect_addr && intersect_addr < addr + size); 1350 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size); 1351 assert(opcode_offset + intersect_size <= bp->GetByteSize()); 1352 1353 // Check for bytes before this breakpoint 1354 const addr_t curr_addr = addr + bytes_written; 1355 if (intersect_addr > curr_addr) 1356 { 1357 // There are some bytes before this breakpoint that we need to 1358 // just write to memory 1359 size_t curr_size = intersect_addr - curr_addr; 1360 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr, 1361 ubuf + bytes_written, 1362 curr_size, 1363 error); 1364 bytes_written += curr_bytes_written; 1365 if (curr_bytes_written != curr_size) 1366 { 1367 // We weren't able to write all of the requested bytes, we 1368 // are done looping and will return the number of bytes that 1369 // we have written so far. 1370 break; 1371 } 1372 } 1373 1374 // Now write any bytes that would cover up any software breakpoints 1375 // directly into the breakpoint opcode buffer 1376 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size); 1377 bytes_written += intersect_size; 1378 } 1379 1380 // Write any remaining bytes after the last breakpoint if we have any left 1381 if (bytes_written < size) 1382 bytes_written += WriteMemoryPrivate (addr + bytes_written, 1383 ubuf + bytes_written, 1384 size - bytes_written, 1385 error); 1386 1387 return bytes_written; 1388 } 1389 1390 addr_t 1391 Process::AllocateMemory(size_t size, uint32_t permissions, Error &error) 1392 { 1393 // Fixme: we should track the blocks we've allocated, and clean them up... 1394 // We could even do our own allocator here if that ends up being more efficient. 1395 return DoAllocateMemory (size, permissions, error); 1396 } 1397 1398 Error 1399 Process::DeallocateMemory (addr_t ptr) 1400 { 1401 return DoDeallocateMemory (ptr); 1402 } 1403 1404 1405 Error 1406 Process::EnableWatchpoint (WatchpointLocation *watchpoint) 1407 { 1408 Error error; 1409 error.SetErrorString("watchpoints are not supported"); 1410 return error; 1411 } 1412 1413 Error 1414 Process::DisableWatchpoint (WatchpointLocation *watchpoint) 1415 { 1416 Error error; 1417 error.SetErrorString("watchpoints are not supported"); 1418 return error; 1419 } 1420 1421 StateType 1422 Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp) 1423 { 1424 StateType state; 1425 // Now wait for the process to launch and return control to us, and then 1426 // call DidLaunch: 1427 while (1) 1428 { 1429 // FIXME: Might want to put a timeout in here: 1430 state = WaitForStateChangedEventsPrivate (NULL, event_sp); 1431 if (state == eStateStopped || state == eStateCrashed || state == eStateExited) 1432 break; 1433 else 1434 HandlePrivateEvent (event_sp); 1435 } 1436 return state; 1437 } 1438 1439 Error 1440 Process::Launch 1441 ( 1442 char const *argv[], 1443 char const *envp[], 1444 uint32_t launch_flags, 1445 const char *stdin_path, 1446 const char *stdout_path, 1447 const char *stderr_path 1448 ) 1449 { 1450 Error error; 1451 m_target_triple.Clear(); 1452 m_abi_sp.reset(); 1453 m_process_input_reader.reset(); 1454 1455 Module *exe_module = m_target.GetExecutableModule().get(); 1456 if (exe_module) 1457 { 1458 char exec_file_path[PATH_MAX]; 1459 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path)); 1460 if (exe_module->GetFileSpec().Exists()) 1461 { 1462 error = WillLaunch (exe_module); 1463 if (error.Success()) 1464 { 1465 SetPublicState (eStateLaunching); 1466 // The args coming in should not contain the application name, the 1467 // lldb_private::Process class will add this in case the executable 1468 // gets resolved to a different file than was given on the command 1469 // line (like when an applicaiton bundle is specified and will 1470 // resolve to the contained exectuable file, or the file given was 1471 // a symlink or other file system link that resolves to a different 1472 // file). 1473 1474 // Get the resolved exectuable path 1475 1476 // Make a new argument vector 1477 std::vector<const char *> exec_path_plus_argv; 1478 // Append the resolved executable path 1479 exec_path_plus_argv.push_back (exec_file_path); 1480 1481 // Push all args if there are any 1482 if (argv) 1483 { 1484 for (int i = 0; argv[i]; ++i) 1485 exec_path_plus_argv.push_back(argv[i]); 1486 } 1487 1488 // Push a NULL to terminate the args. 1489 exec_path_plus_argv.push_back(NULL); 1490 1491 // Now launch using these arguments. 1492 error = DoLaunch (exe_module, 1493 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(), 1494 envp, 1495 launch_flags, 1496 stdin_path, 1497 stdout_path, 1498 stderr_path); 1499 1500 if (error.Fail()) 1501 { 1502 if (GetID() != LLDB_INVALID_PROCESS_ID) 1503 { 1504 SetID (LLDB_INVALID_PROCESS_ID); 1505 const char *error_string = error.AsCString(); 1506 if (error_string == NULL) 1507 error_string = "launch failed"; 1508 SetExitStatus (-1, error_string); 1509 } 1510 } 1511 else 1512 { 1513 EventSP event_sp; 1514 StateType state = WaitForProcessStopPrivate(NULL, event_sp); 1515 1516 if (state == eStateStopped || state == eStateCrashed) 1517 { 1518 DidLaunch (); 1519 1520 // This delays passing the stopped event to listeners till DidLaunch gets 1521 // a chance to complete... 1522 HandlePrivateEvent (event_sp); 1523 StartPrivateStateThread (); 1524 } 1525 else if (state == eStateExited) 1526 { 1527 // We exited while trying to launch somehow. Don't call DidLaunch as that's 1528 // not likely to work, and return an invalid pid. 1529 HandlePrivateEvent (event_sp); 1530 } 1531 } 1532 } 1533 } 1534 else 1535 { 1536 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path); 1537 } 1538 } 1539 return error; 1540 } 1541 1542 Error 1543 Process::CompleteAttach () 1544 { 1545 Error error; 1546 1547 if (GetID() == LLDB_INVALID_PROCESS_ID) 1548 { 1549 error.SetErrorString("no process"); 1550 } 1551 1552 EventSP event_sp; 1553 StateType state = WaitForProcessStopPrivate(NULL, event_sp); 1554 if (state == eStateStopped || state == eStateCrashed) 1555 { 1556 DidAttach (); 1557 // Figure out which one is the executable, and set that in our target: 1558 ModuleList &modules = GetTarget().GetImages(); 1559 1560 size_t num_modules = modules.GetSize(); 1561 for (int i = 0; i < num_modules; i++) 1562 { 1563 ModuleSP module_sp = modules.GetModuleAtIndex(i); 1564 if (module_sp->IsExecutable()) 1565 { 1566 ModuleSP exec_module = GetTarget().GetExecutableModule(); 1567 if (!exec_module || exec_module != module_sp) 1568 { 1569 1570 GetTarget().SetExecutableModule (module_sp, false); 1571 } 1572 break; 1573 } 1574 } 1575 1576 // This delays passing the stopped event to listeners till DidLaunch gets 1577 // a chance to complete... 1578 HandlePrivateEvent(event_sp); 1579 StartPrivateStateThread(); 1580 } 1581 else 1582 { 1583 // We exited while trying to launch somehow. Don't call DidLaunch as that's 1584 // not likely to work, and return an invalid pid. 1585 if (state == eStateExited) 1586 HandlePrivateEvent (event_sp); 1587 error.SetErrorStringWithFormat("invalid state after attach: %s", 1588 lldb_private::StateAsCString(state)); 1589 } 1590 return error; 1591 } 1592 1593 Error 1594 Process::Attach (lldb::pid_t attach_pid) 1595 { 1596 1597 m_target_triple.Clear(); 1598 m_abi_sp.reset(); 1599 m_process_input_reader.reset(); 1600 1601 // Find the process and its architecture. Make sure it matches the architecture 1602 // of the current Target, and if not adjust it. 1603 1604 ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid); 1605 if (attach_spec != GetTarget().GetArchitecture()) 1606 { 1607 // Set the architecture on the target. 1608 GetTarget().SetArchitecture(attach_spec); 1609 } 1610 1611 Error error (WillAttachToProcessWithID(attach_pid)); 1612 if (error.Success()) 1613 { 1614 SetPublicState (eStateAttaching); 1615 1616 error = DoAttachToProcessWithID (attach_pid); 1617 if (error.Success()) 1618 { 1619 error = CompleteAttach(); 1620 } 1621 else 1622 { 1623 if (GetID() != LLDB_INVALID_PROCESS_ID) 1624 { 1625 SetID (LLDB_INVALID_PROCESS_ID); 1626 const char *error_string = error.AsCString(); 1627 if (error_string == NULL) 1628 error_string = "attach failed"; 1629 1630 SetExitStatus(-1, error_string); 1631 } 1632 } 1633 } 1634 return error; 1635 } 1636 1637 Error 1638 Process::Attach (const char *process_name, bool wait_for_launch) 1639 { 1640 m_target_triple.Clear(); 1641 m_abi_sp.reset(); 1642 m_process_input_reader.reset(); 1643 1644 // Find the process and its architecture. Make sure it matches the architecture 1645 // of the current Target, and if not adjust it. 1646 1647 if (!wait_for_launch) 1648 { 1649 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name); 1650 if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture()) 1651 { 1652 // Set the architecture on the target. 1653 GetTarget().SetArchitecture(attach_spec); 1654 } 1655 } 1656 1657 Error error (WillAttachToProcessWithName(process_name, wait_for_launch)); 1658 if (error.Success()) 1659 { 1660 SetPublicState (eStateAttaching); 1661 error = DoAttachToProcessWithName (process_name, wait_for_launch); 1662 if (error.Fail()) 1663 { 1664 if (GetID() != LLDB_INVALID_PROCESS_ID) 1665 { 1666 SetID (LLDB_INVALID_PROCESS_ID); 1667 const char *error_string = error.AsCString(); 1668 if (error_string == NULL) 1669 error_string = "attach failed"; 1670 1671 SetExitStatus(-1, error_string); 1672 } 1673 } 1674 else 1675 { 1676 error = CompleteAttach(); 1677 } 1678 } 1679 return error; 1680 } 1681 1682 Error 1683 Process::Resume () 1684 { 1685 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1686 if (log) 1687 log->Printf("Process::Resume() m_stop_id = %u", m_stop_id); 1688 1689 Error error (WillResume()); 1690 // Tell the process it is about to resume before the thread list 1691 if (error.Success()) 1692 { 1693 // Now let the thread list know we are about to resume so it 1694 // can let all of our threads know that they are about to be 1695 // resumed. Threads will each be called with 1696 // Thread::WillResume(StateType) where StateType contains the state 1697 // that they are supposed to have when the process is resumed 1698 // (suspended/running/stepping). Threads should also check 1699 // their resume signal in lldb::Thread::GetResumeSignal() 1700 // to see if they are suppoed to start back up with a signal. 1701 if (m_thread_list.WillResume()) 1702 { 1703 error = DoResume(); 1704 if (error.Success()) 1705 { 1706 DidResume(); 1707 m_thread_list.DidResume(); 1708 } 1709 } 1710 else 1711 { 1712 error.SetErrorStringWithFormat("thread list returned flase after WillResume"); 1713 } 1714 } 1715 return error; 1716 } 1717 1718 Error 1719 Process::Halt () 1720 { 1721 Error error (WillHalt()); 1722 1723 if (error.Success()) 1724 { 1725 1726 bool caused_stop = false; 1727 EventSP event_sp; 1728 1729 // Pause our private state thread so we can ensure no one else eats 1730 // the stop event out from under us. 1731 PausePrivateStateThread(); 1732 1733 // Ask the process subclass to actually halt our process 1734 error = DoHalt(caused_stop); 1735 if (error.Success()) 1736 { 1737 // If "caused_stop" is true, then DoHalt stopped the process. If 1738 // "caused_stop" is false, the process was already stopped. 1739 // If the DoHalt caused the process to stop, then we want to catch 1740 // this event and set the interrupted bool to true before we pass 1741 // this along so clients know that the process was interrupted by 1742 // a halt command. 1743 if (caused_stop) 1744 { 1745 // Wait for 2 seconds for the process to stop. 1746 TimeValue timeout_time; 1747 timeout_time = TimeValue::Now(); 1748 timeout_time.OffsetWithSeconds(2); 1749 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp); 1750 1751 if (state == eStateInvalid) 1752 { 1753 // We timeout out and didn't get a stop event... 1754 error.SetErrorString ("Halt timed out."); 1755 } 1756 else 1757 { 1758 if (StateIsStoppedState (state)) 1759 { 1760 // We caused the process to interrupt itself, so mark this 1761 // as such in the stop event so clients can tell an interrupted 1762 // process from a natural stop 1763 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true); 1764 } 1765 else 1766 { 1767 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1768 if (log) 1769 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state)); 1770 error.SetErrorString ("Did not get stopped event after halt."); 1771 } 1772 } 1773 } 1774 DidHalt(); 1775 1776 } 1777 // Resume our private state thread before we post the event (if any) 1778 ResumePrivateStateThread(); 1779 1780 // Post any event we might have consumed. If all goes well, we will have 1781 // stopped the process, intercepted the event and set the interrupted 1782 // bool in the event. Post it to the private event queue and that will end up 1783 // correctly setting the state. 1784 if (event_sp) 1785 m_private_state_broadcaster.BroadcastEvent(event_sp); 1786 1787 } 1788 return error; 1789 } 1790 1791 Error 1792 Process::Detach () 1793 { 1794 Error error (WillDetach()); 1795 1796 if (error.Success()) 1797 { 1798 DisableAllBreakpointSites(); 1799 error = DoDetach(); 1800 if (error.Success()) 1801 { 1802 DidDetach(); 1803 StopPrivateStateThread(); 1804 } 1805 } 1806 return error; 1807 } 1808 1809 Error 1810 Process::Destroy () 1811 { 1812 Error error (WillDestroy()); 1813 if (error.Success()) 1814 { 1815 DisableAllBreakpointSites(); 1816 error = DoDestroy(); 1817 if (error.Success()) 1818 { 1819 DidDestroy(); 1820 StopPrivateStateThread(); 1821 } 1822 m_stdio_communication.StopReadThread(); 1823 m_stdio_communication.Disconnect(); 1824 if (m_process_input_reader && m_process_input_reader->IsActive()) 1825 m_target.GetDebugger().PopInputReader (m_process_input_reader); 1826 if (m_process_input_reader) 1827 m_process_input_reader.reset(); 1828 } 1829 return error; 1830 } 1831 1832 Error 1833 Process::Signal (int signal) 1834 { 1835 Error error (WillSignal()); 1836 if (error.Success()) 1837 { 1838 error = DoSignal(signal); 1839 if (error.Success()) 1840 DidSignal(); 1841 } 1842 return error; 1843 } 1844 1845 UnixSignals & 1846 Process::GetUnixSignals () 1847 { 1848 return m_unix_signals; 1849 } 1850 1851 Target & 1852 Process::GetTarget () 1853 { 1854 return m_target; 1855 } 1856 1857 const Target & 1858 Process::GetTarget () const 1859 { 1860 return m_target; 1861 } 1862 1863 uint32_t 1864 Process::GetAddressByteSize() 1865 { 1866 if (m_addr_byte_size == 0) 1867 return m_target.GetArchitecture().GetAddressByteSize(); 1868 return m_addr_byte_size; 1869 } 1870 1871 bool 1872 Process::ShouldBroadcastEvent (Event *event_ptr) 1873 { 1874 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr); 1875 bool return_value = true; 1876 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS)); 1877 1878 switch (state) 1879 { 1880 case eStateAttaching: 1881 case eStateLaunching: 1882 case eStateDetached: 1883 case eStateExited: 1884 case eStateUnloaded: 1885 // These events indicate changes in the state of the debugging session, always report them. 1886 return_value = true; 1887 break; 1888 case eStateInvalid: 1889 // We stopped for no apparent reason, don't report it. 1890 return_value = false; 1891 break; 1892 case eStateRunning: 1893 case eStateStepping: 1894 // If we've started the target running, we handle the cases where we 1895 // are already running and where there is a transition from stopped to 1896 // running differently. 1897 // running -> running: Automatically suppress extra running events 1898 // stopped -> running: Report except when there is one or more no votes 1899 // and no yes votes. 1900 SynchronouslyNotifyStateChanged (state); 1901 switch (m_public_state.GetValue()) 1902 { 1903 case eStateRunning: 1904 case eStateStepping: 1905 // We always suppress multiple runnings with no PUBLIC stop in between. 1906 return_value = false; 1907 break; 1908 default: 1909 // TODO: make this work correctly. For now always report 1910 // run if we aren't running so we don't miss any runnning 1911 // events. If I run the lldb/test/thread/a.out file and 1912 // break at main.cpp:58, run and hit the breakpoints on 1913 // multiple threads, then somehow during the stepping over 1914 // of all breakpoints no run gets reported. 1915 return_value = true; 1916 1917 // This is a transition from stop to run. 1918 switch (m_thread_list.ShouldReportRun (event_ptr)) 1919 { 1920 case eVoteYes: 1921 case eVoteNoOpinion: 1922 return_value = true; 1923 break; 1924 case eVoteNo: 1925 return_value = false; 1926 break; 1927 } 1928 break; 1929 } 1930 break; 1931 case eStateStopped: 1932 case eStateCrashed: 1933 case eStateSuspended: 1934 { 1935 // We've stopped. First see if we're going to restart the target. 1936 // If we are going to stop, then we always broadcast the event. 1937 // If we aren't going to stop, let the thread plans decide if we're going to report this event. 1938 // If no thread has an opinion, we don't report it. 1939 if (ProcessEventData::GetInterruptedFromEvent (event_ptr)) 1940 { 1941 if (log) 1942 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state)); 1943 return true; 1944 } 1945 else 1946 { 1947 RefreshStateAfterStop (); 1948 1949 if (m_thread_list.ShouldStop (event_ptr) == false) 1950 { 1951 switch (m_thread_list.ShouldReportStop (event_ptr)) 1952 { 1953 case eVoteYes: 1954 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true); 1955 // Intentional fall-through here. 1956 case eVoteNoOpinion: 1957 case eVoteNo: 1958 return_value = false; 1959 break; 1960 } 1961 1962 if (log) 1963 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state)); 1964 Resume (); 1965 } 1966 else 1967 { 1968 return_value = true; 1969 SynchronouslyNotifyStateChanged (state); 1970 } 1971 } 1972 } 1973 } 1974 1975 if (log) 1976 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO"); 1977 return return_value; 1978 } 1979 1980 //------------------------------------------------------------------ 1981 // Thread Queries 1982 //------------------------------------------------------------------ 1983 1984 ThreadList & 1985 Process::GetThreadList () 1986 { 1987 return m_thread_list; 1988 } 1989 1990 const ThreadList & 1991 Process::GetThreadList () const 1992 { 1993 return m_thread_list; 1994 } 1995 1996 1997 bool 1998 Process::StartPrivateStateThread () 1999 { 2000 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS)); 2001 2002 if (log) 2003 log->Printf ("Process::%s ( )", __FUNCTION__); 2004 2005 // Create a thread that watches our internal state and controls which 2006 // events make it to clients (into the DCProcess event queue). 2007 char thread_name[1024]; 2008 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID()); 2009 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL); 2010 return m_private_state_thread != LLDB_INVALID_HOST_THREAD; 2011 } 2012 2013 void 2014 Process::PausePrivateStateThread () 2015 { 2016 ControlPrivateStateThread (eBroadcastInternalStateControlPause); 2017 } 2018 2019 void 2020 Process::ResumePrivateStateThread () 2021 { 2022 ControlPrivateStateThread (eBroadcastInternalStateControlResume); 2023 } 2024 2025 void 2026 Process::StopPrivateStateThread () 2027 { 2028 ControlPrivateStateThread (eBroadcastInternalStateControlStop); 2029 } 2030 2031 void 2032 Process::ControlPrivateStateThread (uint32_t signal) 2033 { 2034 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS)); 2035 2036 assert (signal == eBroadcastInternalStateControlStop || 2037 signal == eBroadcastInternalStateControlPause || 2038 signal == eBroadcastInternalStateControlResume); 2039 2040 if (log) 2041 log->Printf ("Process::%s ( ) - signal: %d", __FUNCTION__, signal); 2042 2043 // Signal the private state thread 2044 if (m_private_state_thread != LLDB_INVALID_HOST_THREAD) 2045 { 2046 TimeValue timeout_time; 2047 bool timed_out; 2048 2049 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL); 2050 2051 timeout_time = TimeValue::Now(); 2052 timeout_time.OffsetWithSeconds(2); 2053 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out); 2054 m_private_state_control_wait.SetValue (false, eBroadcastNever); 2055 2056 if (signal == eBroadcastInternalStateControlStop) 2057 { 2058 if (timed_out) 2059 Host::ThreadCancel (m_private_state_thread, NULL); 2060 2061 thread_result_t result = NULL; 2062 Host::ThreadJoin (m_private_state_thread, &result, NULL); 2063 m_private_state_thread = LLDB_INVALID_HOST_THREAD; 2064 } 2065 } 2066 } 2067 2068 void 2069 Process::HandlePrivateEvent (EventSP &event_sp) 2070 { 2071 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2072 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 2073 // See if we should broadcast this state to external clients? 2074 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get()); 2075 if (log) 2076 log->Printf ("Process::%s (arg = %p, pid = %i) got event '%s' broadcast = %s", __FUNCTION__, this, GetID(), StateAsCString(internal_state), should_broadcast ? "yes" : "no"); 2077 2078 if (should_broadcast) 2079 { 2080 if (log) 2081 { 2082 log->Printf ("\tChanging public state from: %s to %s", StateAsCString(GetState ()), StateAsCString (internal_state)); 2083 } 2084 if (StateIsRunningState (internal_state)) 2085 PushProcessInputReader (); 2086 else 2087 PopProcessInputReader (); 2088 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get()); 2089 BroadcastEvent (event_sp); 2090 } 2091 else 2092 { 2093 if (log) 2094 { 2095 log->Printf ("\tNot changing public state with event: %s", StateAsCString (internal_state)); 2096 } 2097 } 2098 } 2099 2100 void * 2101 Process::PrivateStateThread (void *arg) 2102 { 2103 Process *proc = static_cast<Process*> (arg); 2104 void *result = proc->RunPrivateStateThread (); 2105 return result; 2106 } 2107 2108 void * 2109 Process::RunPrivateStateThread () 2110 { 2111 bool control_only = false; 2112 m_private_state_control_wait.SetValue (false, eBroadcastNever); 2113 2114 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2115 if (log) 2116 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID()); 2117 2118 bool exit_now = false; 2119 while (!exit_now) 2120 { 2121 EventSP event_sp; 2122 WaitForEventsPrivate (NULL, event_sp, control_only); 2123 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) 2124 { 2125 switch (event_sp->GetType()) 2126 { 2127 case eBroadcastInternalStateControlStop: 2128 exit_now = true; 2129 continue; // Go to next loop iteration so we exit without 2130 break; // doing any internal state managment below 2131 2132 case eBroadcastInternalStateControlPause: 2133 control_only = true; 2134 break; 2135 2136 case eBroadcastInternalStateControlResume: 2137 control_only = false; 2138 break; 2139 } 2140 2141 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS); 2142 if (log) 2143 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType()); 2144 2145 m_private_state_control_wait.SetValue (true, eBroadcastAlways); 2146 continue; 2147 } 2148 2149 2150 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 2151 2152 if (internal_state != eStateInvalid) 2153 { 2154 HandlePrivateEvent (event_sp); 2155 } 2156 2157 if (internal_state == eStateInvalid || 2158 internal_state == eStateExited || 2159 internal_state == eStateDetached ) 2160 { 2161 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS); 2162 if (log) 2163 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state)); 2164 2165 break; 2166 } 2167 } 2168 2169 // Verify log is still enabled before attempting to write to it... 2170 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS); 2171 if (log) 2172 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID()); 2173 2174 m_private_state_thread = LLDB_INVALID_HOST_THREAD; 2175 return NULL; 2176 } 2177 2178 //------------------------------------------------------------------ 2179 // Process Event Data 2180 //------------------------------------------------------------------ 2181 2182 Process::ProcessEventData::ProcessEventData () : 2183 EventData (), 2184 m_process_sp (), 2185 m_state (eStateInvalid), 2186 m_restarted (false), 2187 m_update_state (false), 2188 m_interrupted (false) 2189 { 2190 } 2191 2192 Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) : 2193 EventData (), 2194 m_process_sp (process_sp), 2195 m_state (state), 2196 m_restarted (false), 2197 m_update_state (false), 2198 m_interrupted (false) 2199 { 2200 } 2201 2202 Process::ProcessEventData::~ProcessEventData() 2203 { 2204 } 2205 2206 const ConstString & 2207 Process::ProcessEventData::GetFlavorString () 2208 { 2209 static ConstString g_flavor ("Process::ProcessEventData"); 2210 return g_flavor; 2211 } 2212 2213 const ConstString & 2214 Process::ProcessEventData::GetFlavor () const 2215 { 2216 return ProcessEventData::GetFlavorString (); 2217 } 2218 2219 void 2220 Process::ProcessEventData::DoOnRemoval (Event *event_ptr) 2221 { 2222 // This function gets called twice for each event, once when the event gets pulled 2223 // off of the private process event queue, and once when it gets pulled off of 2224 // the public event queue. m_update_state is used to distinguish these 2225 // two cases; it is false when we're just pulling it off for private handling, 2226 // and we don't want to do the breakpoint command handling then. 2227 2228 if (!m_update_state) 2229 return; 2230 2231 m_process_sp->SetPublicState (m_state); 2232 2233 // If we're stopped and haven't restarted, then do the breakpoint commands here: 2234 if (m_state == eStateStopped && ! m_restarted) 2235 { 2236 int num_threads = m_process_sp->GetThreadList().GetSize(); 2237 int idx; 2238 2239 for (idx = 0; idx < num_threads; ++idx) 2240 { 2241 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx); 2242 2243 StopInfoSP stop_info_sp = thread_sp->GetStopInfo (); 2244 if (stop_info_sp) 2245 { 2246 stop_info_sp->PerformAction(event_ptr); 2247 } 2248 } 2249 2250 // The stop action might restart the target. If it does, then we want to mark that in the 2251 // event so that whoever is receiving it will know to wait for the running event and reflect 2252 // that state appropriately. 2253 2254 if (m_process_sp->GetPrivateState() == eStateRunning) 2255 SetRestarted(true); 2256 } 2257 } 2258 2259 void 2260 Process::ProcessEventData::Dump (Stream *s) const 2261 { 2262 if (m_process_sp) 2263 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID()); 2264 2265 s->Printf("state = %s", StateAsCString(GetState()));; 2266 } 2267 2268 const Process::ProcessEventData * 2269 Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr) 2270 { 2271 if (event_ptr) 2272 { 2273 const EventData *event_data = event_ptr->GetData(); 2274 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString()) 2275 return static_cast <const ProcessEventData *> (event_ptr->GetData()); 2276 } 2277 return NULL; 2278 } 2279 2280 ProcessSP 2281 Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr) 2282 { 2283 ProcessSP process_sp; 2284 const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 2285 if (data) 2286 process_sp = data->GetProcessSP(); 2287 return process_sp; 2288 } 2289 2290 StateType 2291 Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr) 2292 { 2293 const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 2294 if (data == NULL) 2295 return eStateInvalid; 2296 else 2297 return data->GetState(); 2298 } 2299 2300 bool 2301 Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr) 2302 { 2303 const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 2304 if (data == NULL) 2305 return false; 2306 else 2307 return data->GetRestarted(); 2308 } 2309 2310 void 2311 Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value) 2312 { 2313 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 2314 if (data != NULL) 2315 data->SetRestarted(new_value); 2316 } 2317 2318 bool 2319 Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr) 2320 { 2321 const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 2322 if (data == NULL) 2323 return false; 2324 else 2325 return data->GetInterrupted (); 2326 } 2327 2328 void 2329 Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value) 2330 { 2331 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 2332 if (data != NULL) 2333 data->SetInterrupted(new_value); 2334 } 2335 2336 bool 2337 Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr) 2338 { 2339 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 2340 if (data) 2341 { 2342 data->SetUpdateStateOnRemoval(); 2343 return true; 2344 } 2345 return false; 2346 } 2347 2348 Target * 2349 Process::CalculateTarget () 2350 { 2351 return &m_target; 2352 } 2353 2354 Process * 2355 Process::CalculateProcess () 2356 { 2357 return this; 2358 } 2359 2360 Thread * 2361 Process::CalculateThread () 2362 { 2363 return NULL; 2364 } 2365 2366 StackFrame * 2367 Process::CalculateStackFrame () 2368 { 2369 return NULL; 2370 } 2371 2372 void 2373 Process::CalculateExecutionContext (ExecutionContext &exe_ctx) 2374 { 2375 exe_ctx.target = &m_target; 2376 exe_ctx.process = this; 2377 exe_ctx.thread = NULL; 2378 exe_ctx.frame = NULL; 2379 } 2380 2381 lldb::ProcessSP 2382 Process::GetSP () 2383 { 2384 return GetTarget().GetProcessSP(); 2385 } 2386 2387 uint32_t 2388 Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids) 2389 { 2390 return 0; 2391 } 2392 2393 ArchSpec 2394 Process::GetArchSpecForExistingProcess (lldb::pid_t pid) 2395 { 2396 return Host::GetArchSpecForExistingProcess (pid); 2397 } 2398 2399 ArchSpec 2400 Process::GetArchSpecForExistingProcess (const char *process_name) 2401 { 2402 return Host::GetArchSpecForExistingProcess (process_name); 2403 } 2404 2405 void 2406 Process::AppendSTDOUT (const char * s, size_t len) 2407 { 2408 Mutex::Locker locker (m_stdio_communication_mutex); 2409 m_stdout_data.append (s, len); 2410 2411 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState())); 2412 } 2413 2414 void 2415 Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len) 2416 { 2417 Process *process = (Process *) baton; 2418 process->AppendSTDOUT (static_cast<const char *>(src), src_len); 2419 } 2420 2421 size_t 2422 Process::ProcessInputReaderCallback (void *baton, 2423 InputReader &reader, 2424 lldb::InputReaderAction notification, 2425 const char *bytes, 2426 size_t bytes_len) 2427 { 2428 Process *process = (Process *) baton; 2429 2430 switch (notification) 2431 { 2432 case eInputReaderActivate: 2433 break; 2434 2435 case eInputReaderDeactivate: 2436 break; 2437 2438 case eInputReaderReactivate: 2439 break; 2440 2441 case eInputReaderGotToken: 2442 { 2443 Error error; 2444 process->PutSTDIN (bytes, bytes_len, error); 2445 } 2446 break; 2447 2448 case eInputReaderInterrupt: 2449 process->Halt (); 2450 break; 2451 2452 case eInputReaderEndOfFile: 2453 process->AppendSTDOUT ("^D", 2); 2454 break; 2455 2456 case eInputReaderDone: 2457 break; 2458 2459 } 2460 2461 return bytes_len; 2462 } 2463 2464 void 2465 Process::ResetProcessInputReader () 2466 { 2467 m_process_input_reader.reset(); 2468 } 2469 2470 void 2471 Process::SetUpProcessInputReader (int file_descriptor) 2472 { 2473 // First set up the Read Thread for reading/handling process I/O 2474 2475 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true)); 2476 2477 if (conn_ap.get()) 2478 { 2479 m_stdio_communication.SetConnection (conn_ap.release()); 2480 if (m_stdio_communication.IsConnected()) 2481 { 2482 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this); 2483 m_stdio_communication.StartReadThread(); 2484 2485 // Now read thread is set up, set up input reader. 2486 2487 if (!m_process_input_reader.get()) 2488 { 2489 m_process_input_reader.reset (new InputReader(m_target.GetDebugger())); 2490 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback, 2491 this, 2492 eInputReaderGranularityByte, 2493 NULL, 2494 NULL, 2495 false)); 2496 2497 if (err.Fail()) 2498 m_process_input_reader.reset(); 2499 } 2500 } 2501 } 2502 } 2503 2504 void 2505 Process::PushProcessInputReader () 2506 { 2507 if (m_process_input_reader && !m_process_input_reader->IsActive()) 2508 m_target.GetDebugger().PushInputReader (m_process_input_reader); 2509 } 2510 2511 void 2512 Process::PopProcessInputReader () 2513 { 2514 if (m_process_input_reader && m_process_input_reader->IsActive()) 2515 m_target.GetDebugger().PopInputReader (m_process_input_reader); 2516 } 2517 2518 2519 void 2520 Process::Initialize () 2521 { 2522 UserSettingsControllerSP &usc = GetSettingsController(); 2523 usc.reset (new SettingsController); 2524 UserSettingsController::InitializeSettingsController (usc, 2525 SettingsController::global_settings_table, 2526 SettingsController::instance_settings_table); 2527 } 2528 2529 void 2530 Process::Terminate () 2531 { 2532 UserSettingsControllerSP &usc = GetSettingsController(); 2533 UserSettingsController::FinalizeSettingsController (usc); 2534 usc.reset(); 2535 } 2536 2537 UserSettingsControllerSP & 2538 Process::GetSettingsController () 2539 { 2540 static UserSettingsControllerSP g_settings_controller; 2541 return g_settings_controller; 2542 } 2543 2544 void 2545 Process::UpdateInstanceName () 2546 { 2547 ModuleSP module_sp = GetTarget().GetExecutableModule(); 2548 if (module_sp) 2549 { 2550 StreamString sstr; 2551 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString()); 2552 2553 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(), 2554 sstr.GetData()); 2555 } 2556 } 2557 2558 ExecutionResults 2559 Process::RunThreadPlan (ExecutionContext &exe_ctx, 2560 lldb::ThreadPlanSP &thread_plan_sp, 2561 bool stop_others, 2562 bool try_all_threads, 2563 bool discard_on_error, 2564 uint32_t single_thread_timeout_usec, 2565 Stream &errors) 2566 { 2567 ExecutionResults return_value = eExecutionSetupError; 2568 2569 // Save this value for restoration of the execution context after we run 2570 uint32_t tid = exe_ctx.thread->GetIndexID(); 2571 2572 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either, 2573 // so we should arrange to reset them as well. 2574 2575 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread(); 2576 lldb::StackFrameSP selected_frame_sp; 2577 2578 uint32_t selected_tid; 2579 if (selected_thread_sp != NULL) 2580 { 2581 selected_tid = selected_thread_sp->GetIndexID(); 2582 selected_frame_sp = selected_thread_sp->GetSelectedFrame(); 2583 } 2584 else 2585 { 2586 selected_tid = LLDB_INVALID_THREAD_ID; 2587 } 2588 2589 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true); 2590 2591 Listener listener("ClangFunction temporary listener"); 2592 exe_ctx.process->HijackProcessEvents(&listener); 2593 2594 Error resume_error = exe_ctx.process->Resume (); 2595 if (!resume_error.Success()) 2596 { 2597 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString()); 2598 exe_ctx.process->RestoreProcessEvents(); 2599 return lldb::eExecutionSetupError; 2600 } 2601 2602 // We need to call the function synchronously, so spin waiting for it to return. 2603 // If we get interrupted while executing, we're going to lose our context, and 2604 // won't be able to gather the result at this point. 2605 // We set the timeout AFTER the resume, since the resume takes some time and we 2606 // don't want to charge that to the timeout. 2607 2608 TimeValue* timeout_ptr = NULL; 2609 TimeValue real_timeout; 2610 2611 if (single_thread_timeout_usec != 0) 2612 { 2613 real_timeout = TimeValue::Now(); 2614 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec); 2615 timeout_ptr = &real_timeout; 2616 } 2617 2618 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 2619 while (1) 2620 { 2621 lldb::EventSP event_sp; 2622 lldb::StateType stop_state = lldb::eStateInvalid; 2623 // Now wait for the process to stop again: 2624 bool got_event = listener.WaitForEvent (timeout_ptr, event_sp); 2625 2626 if (!got_event) 2627 { 2628 // Right now this is the only way to tell we've timed out... 2629 // We should interrupt the process here... 2630 // Not really sure what to do if Halt fails here... 2631 if (log) 2632 if (try_all_threads) 2633 log->Printf ("Running function with timeout: %d timed out, trying with all threads enabled.", 2634 single_thread_timeout_usec); 2635 else 2636 log->Printf ("Running function with timeout: %d timed out, abandoning execution.", 2637 single_thread_timeout_usec); 2638 2639 if (exe_ctx.process->Halt().Success()) 2640 { 2641 timeout_ptr = NULL; 2642 if (log) 2643 log->Printf ("Halt succeeded."); 2644 2645 // Between the time that we got the timeout and the time we halted, but target 2646 // might have actually completed the plan. If so, we're done. Note, I call WFE here with a short 2647 // timeout to 2648 got_event = listener.WaitForEvent(NULL, event_sp); 2649 2650 if (got_event) 2651 { 2652 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 2653 if (log) 2654 { 2655 log->Printf ("Stopped with event: %s", StateAsCString(stop_state)); 2656 if (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get())) 2657 log->Printf (" Event was the Halt interruption event."); 2658 } 2659 2660 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get())) 2661 { 2662 if (log) 2663 log->Printf ("Even though we timed out, the call plan was done. Exiting wait loop."); 2664 return_value = lldb::eExecutionCompleted; 2665 break; 2666 } 2667 2668 if (try_all_threads 2669 && (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent (event_sp.get()))) 2670 { 2671 2672 thread_plan_sp->SetStopOthers (false); 2673 if (log) 2674 log->Printf ("About to resume."); 2675 2676 exe_ctx.process->Resume(); 2677 continue; 2678 } 2679 else 2680 { 2681 exe_ctx.process->RestoreProcessEvents (); 2682 return lldb::eExecutionInterrupted; 2683 } 2684 } 2685 } 2686 } 2687 2688 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 2689 if (log) 2690 log->Printf("Got event: %s.", StateAsCString(stop_state)); 2691 2692 if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping) 2693 continue; 2694 2695 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get())) 2696 { 2697 return_value = lldb::eExecutionCompleted; 2698 break; 2699 } 2700 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get())) 2701 { 2702 return_value = lldb::eExecutionDiscarded; 2703 break; 2704 } 2705 else 2706 { 2707 if (log) 2708 { 2709 StreamString s; 2710 event_sp->Dump (&s); 2711 StreamString ts; 2712 2713 const char *event_explanation; 2714 2715 do 2716 { 2717 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get()); 2718 2719 if (!event_data) 2720 { 2721 event_explanation = "<no event data>"; 2722 break; 2723 } 2724 2725 Process *process = event_data->GetProcessSP().get(); 2726 2727 if (!process) 2728 { 2729 event_explanation = "<no process>"; 2730 break; 2731 } 2732 2733 ThreadList &thread_list = process->GetThreadList(); 2734 2735 uint32_t num_threads = thread_list.GetSize(); 2736 uint32_t thread_index; 2737 2738 ts.Printf("<%u threads> ", num_threads); 2739 2740 for (thread_index = 0; 2741 thread_index < num_threads; 2742 ++thread_index) 2743 { 2744 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get(); 2745 2746 if (!thread) 2747 { 2748 ts.Printf("<?> "); 2749 continue; 2750 } 2751 2752 ts.Printf("<"); 2753 RegisterContext *register_context = thread->GetRegisterContext().get(); 2754 2755 if (register_context) 2756 ts.Printf("[ip 0x%llx] ", register_context->GetPC()); 2757 else 2758 ts.Printf("[ip unknown] "); 2759 2760 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo(); 2761 if (stop_info_sp) 2762 { 2763 const char *stop_desc = stop_info_sp->GetDescription(); 2764 if (stop_desc) 2765 ts.PutCString (stop_desc); 2766 } 2767 ts.Printf(">"); 2768 } 2769 2770 event_explanation = ts.GetData(); 2771 } while (0); 2772 2773 if (log) 2774 log->Printf("Execution interrupted: %s %s", s.GetData(), event_explanation); 2775 } 2776 2777 if (discard_on_error && thread_plan_sp) 2778 { 2779 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp); 2780 } 2781 return_value = lldb::eExecutionInterrupted; 2782 break; 2783 } 2784 } 2785 2786 if (exe_ctx.process) 2787 exe_ctx.process->RestoreProcessEvents (); 2788 2789 // Thread we ran the function in may have gone away because we ran the target 2790 // Check that it's still there. 2791 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get(); 2792 if (exe_ctx.thread) 2793 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get(); 2794 2795 // Also restore the current process'es selected frame & thread, since this function calling may 2796 // be done behind the user's back. 2797 2798 if (selected_tid != LLDB_INVALID_THREAD_ID) 2799 { 2800 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid)) 2801 { 2802 // We were able to restore the selected thread, now restore the frame: 2803 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get()); 2804 } 2805 } 2806 2807 return return_value; 2808 } 2809 2810 const char * 2811 Process::ExecutionResultAsCString (ExecutionResults result) 2812 { 2813 const char *result_name; 2814 2815 switch (result) 2816 { 2817 case lldb::eExecutionCompleted: 2818 result_name = "eExecutionCompleted"; 2819 break; 2820 case lldb::eExecutionDiscarded: 2821 result_name = "eExecutionDiscarded"; 2822 break; 2823 case lldb::eExecutionInterrupted: 2824 result_name = "eExecutionInterrupted"; 2825 break; 2826 case lldb::eExecutionSetupError: 2827 result_name = "eExecutionSetupError"; 2828 break; 2829 case lldb::eExecutionTimedOut: 2830 result_name = "eExecutionTimedOut"; 2831 break; 2832 } 2833 return result_name; 2834 } 2835 2836 //-------------------------------------------------------------- 2837 // class Process::SettingsController 2838 //-------------------------------------------------------------- 2839 2840 Process::SettingsController::SettingsController () : 2841 UserSettingsController ("process", Target::GetSettingsController()) 2842 { 2843 m_default_settings.reset (new ProcessInstanceSettings (*this, 2844 false, 2845 InstanceSettings::GetDefaultName().AsCString())); 2846 } 2847 2848 Process::SettingsController::~SettingsController () 2849 { 2850 } 2851 2852 lldb::InstanceSettingsSP 2853 Process::SettingsController::CreateInstanceSettings (const char *instance_name) 2854 { 2855 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(), 2856 false, 2857 instance_name); 2858 lldb::InstanceSettingsSP new_settings_sp (new_settings); 2859 return new_settings_sp; 2860 } 2861 2862 //-------------------------------------------------------------- 2863 // class ProcessInstanceSettings 2864 //-------------------------------------------------------------- 2865 2866 ProcessInstanceSettings::ProcessInstanceSettings 2867 ( 2868 UserSettingsController &owner, 2869 bool live_instance, 2870 const char *name 2871 ) : 2872 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance), 2873 m_run_args (), 2874 m_env_vars (), 2875 m_input_path (), 2876 m_output_path (), 2877 m_error_path (), 2878 m_plugin (), 2879 m_disable_aslr (true), 2880 m_disable_stdio (false), 2881 m_inherit_host_env (true), 2882 m_got_host_env (false) 2883 { 2884 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called 2885 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers. 2886 // For this reason it has to be called here, rather than in the initializer or in the parent constructor. 2887 // This is true for CreateInstanceName() too. 2888 2889 if (GetInstanceName () == InstanceSettings::InvalidName()) 2890 { 2891 ChangeInstanceName (std::string (CreateInstanceName().AsCString())); 2892 m_owner.RegisterInstanceSettings (this); 2893 } 2894 2895 if (live_instance) 2896 { 2897 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name); 2898 CopyInstanceSettings (pending_settings,false); 2899 //m_owner.RemovePendingSettings (m_instance_name); 2900 } 2901 } 2902 2903 ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) : 2904 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()), 2905 m_run_args (rhs.m_run_args), 2906 m_env_vars (rhs.m_env_vars), 2907 m_input_path (rhs.m_input_path), 2908 m_output_path (rhs.m_output_path), 2909 m_error_path (rhs.m_error_path), 2910 m_plugin (rhs.m_plugin), 2911 m_disable_aslr (rhs.m_disable_aslr), 2912 m_disable_stdio (rhs.m_disable_stdio) 2913 { 2914 if (m_instance_name != InstanceSettings::GetDefaultName()) 2915 { 2916 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name); 2917 CopyInstanceSettings (pending_settings,false); 2918 m_owner.RemovePendingSettings (m_instance_name); 2919 } 2920 } 2921 2922 ProcessInstanceSettings::~ProcessInstanceSettings () 2923 { 2924 } 2925 2926 ProcessInstanceSettings& 2927 ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs) 2928 { 2929 if (this != &rhs) 2930 { 2931 m_run_args = rhs.m_run_args; 2932 m_env_vars = rhs.m_env_vars; 2933 m_input_path = rhs.m_input_path; 2934 m_output_path = rhs.m_output_path; 2935 m_error_path = rhs.m_error_path; 2936 m_plugin = rhs.m_plugin; 2937 m_disable_aslr = rhs.m_disable_aslr; 2938 m_disable_stdio = rhs.m_disable_stdio; 2939 m_inherit_host_env = rhs.m_inherit_host_env; 2940 } 2941 2942 return *this; 2943 } 2944 2945 2946 void 2947 ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name, 2948 const char *index_value, 2949 const char *value, 2950 const ConstString &instance_name, 2951 const SettingEntry &entry, 2952 lldb::VarSetOperationType op, 2953 Error &err, 2954 bool pending) 2955 { 2956 if (var_name == RunArgsVarName()) 2957 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err); 2958 else if (var_name == EnvVarsVarName()) 2959 { 2960 GetHostEnvironmentIfNeeded (); 2961 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err); 2962 } 2963 else if (var_name == InputPathVarName()) 2964 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err); 2965 else if (var_name == OutputPathVarName()) 2966 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err); 2967 else if (var_name == ErrorPathVarName()) 2968 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err); 2969 else if (var_name == PluginVarName()) 2970 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err); 2971 else if (var_name == InheritHostEnvVarName()) 2972 UserSettingsController::UpdateBooleanVariable (op, m_inherit_host_env, value, err); 2973 else if (var_name == DisableASLRVarName()) 2974 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err); 2975 else if (var_name == DisableSTDIOVarName ()) 2976 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err); 2977 } 2978 2979 void 2980 ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings, 2981 bool pending) 2982 { 2983 if (new_settings.get() == NULL) 2984 return; 2985 2986 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get(); 2987 2988 m_run_args = new_process_settings->m_run_args; 2989 m_env_vars = new_process_settings->m_env_vars; 2990 m_input_path = new_process_settings->m_input_path; 2991 m_output_path = new_process_settings->m_output_path; 2992 m_error_path = new_process_settings->m_error_path; 2993 m_plugin = new_process_settings->m_plugin; 2994 m_disable_aslr = new_process_settings->m_disable_aslr; 2995 m_disable_stdio = new_process_settings->m_disable_stdio; 2996 } 2997 2998 bool 2999 ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry, 3000 const ConstString &var_name, 3001 StringList &value, 3002 Error *err) 3003 { 3004 if (var_name == RunArgsVarName()) 3005 { 3006 if (m_run_args.GetArgumentCount() > 0) 3007 { 3008 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i) 3009 value.AppendString (m_run_args.GetArgumentAtIndex (i)); 3010 } 3011 } 3012 else if (var_name == EnvVarsVarName()) 3013 { 3014 GetHostEnvironmentIfNeeded (); 3015 3016 if (m_env_vars.size() > 0) 3017 { 3018 std::map<std::string, std::string>::iterator pos; 3019 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos) 3020 { 3021 StreamString value_str; 3022 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str()); 3023 value.AppendString (value_str.GetData()); 3024 } 3025 } 3026 } 3027 else if (var_name == InputPathVarName()) 3028 { 3029 value.AppendString (m_input_path.c_str()); 3030 } 3031 else if (var_name == OutputPathVarName()) 3032 { 3033 value.AppendString (m_output_path.c_str()); 3034 } 3035 else if (var_name == ErrorPathVarName()) 3036 { 3037 value.AppendString (m_error_path.c_str()); 3038 } 3039 else if (var_name == PluginVarName()) 3040 { 3041 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin)); 3042 } 3043 else if (var_name == InheritHostEnvVarName()) 3044 { 3045 if (m_inherit_host_env) 3046 value.AppendString ("true"); 3047 else 3048 value.AppendString ("false"); 3049 } 3050 else if (var_name == DisableASLRVarName()) 3051 { 3052 if (m_disable_aslr) 3053 value.AppendString ("true"); 3054 else 3055 value.AppendString ("false"); 3056 } 3057 else if (var_name == DisableSTDIOVarName()) 3058 { 3059 if (m_disable_stdio) 3060 value.AppendString ("true"); 3061 else 3062 value.AppendString ("false"); 3063 } 3064 else 3065 { 3066 if (err) 3067 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString()); 3068 return false; 3069 } 3070 return true; 3071 } 3072 3073 const ConstString 3074 ProcessInstanceSettings::CreateInstanceName () 3075 { 3076 static int instance_count = 1; 3077 StreamString sstr; 3078 3079 sstr.Printf ("process_%d", instance_count); 3080 ++instance_count; 3081 3082 const ConstString ret_val (sstr.GetData()); 3083 return ret_val; 3084 } 3085 3086 const ConstString & 3087 ProcessInstanceSettings::RunArgsVarName () 3088 { 3089 static ConstString run_args_var_name ("run-args"); 3090 3091 return run_args_var_name; 3092 } 3093 3094 const ConstString & 3095 ProcessInstanceSettings::EnvVarsVarName () 3096 { 3097 static ConstString env_vars_var_name ("env-vars"); 3098 3099 return env_vars_var_name; 3100 } 3101 3102 const ConstString & 3103 ProcessInstanceSettings::InheritHostEnvVarName () 3104 { 3105 static ConstString g_name ("inherit-env"); 3106 3107 return g_name; 3108 } 3109 3110 const ConstString & 3111 ProcessInstanceSettings::InputPathVarName () 3112 { 3113 static ConstString input_path_var_name ("input-path"); 3114 3115 return input_path_var_name; 3116 } 3117 3118 const ConstString & 3119 ProcessInstanceSettings::OutputPathVarName () 3120 { 3121 static ConstString output_path_var_name ("output-path"); 3122 3123 return output_path_var_name; 3124 } 3125 3126 const ConstString & 3127 ProcessInstanceSettings::ErrorPathVarName () 3128 { 3129 static ConstString error_path_var_name ("error-path"); 3130 3131 return error_path_var_name; 3132 } 3133 3134 const ConstString & 3135 ProcessInstanceSettings::PluginVarName () 3136 { 3137 static ConstString plugin_var_name ("plugin"); 3138 3139 return plugin_var_name; 3140 } 3141 3142 3143 const ConstString & 3144 ProcessInstanceSettings::DisableASLRVarName () 3145 { 3146 static ConstString disable_aslr_var_name ("disable-aslr"); 3147 3148 return disable_aslr_var_name; 3149 } 3150 3151 const ConstString & 3152 ProcessInstanceSettings::DisableSTDIOVarName () 3153 { 3154 static ConstString disable_stdio_var_name ("disable-stdio"); 3155 3156 return disable_stdio_var_name; 3157 } 3158 3159 //-------------------------------------------------- 3160 // SettingsController Variable Tables 3161 //-------------------------------------------------- 3162 3163 SettingEntry 3164 Process::SettingsController::global_settings_table[] = 3165 { 3166 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"}, 3167 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL } 3168 }; 3169 3170 3171 lldb::OptionEnumValueElement 3172 Process::SettingsController::g_plugins[] = 3173 { 3174 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" }, 3175 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" }, 3176 { 0, NULL, NULL } 3177 }; 3178 3179 SettingEntry 3180 Process::SettingsController::instance_settings_table[] = 3181 { 3182 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"}, 3183 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." }, 3184 { "env-vars", eSetVarTypeDictionary, NULL, NULL, false, false, "A list of all the environment variables to be passed to the executable's environment, and their values." }, 3185 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." }, 3186 { "input-path", eSetVarTypeString, "/dev/stdin", NULL, false, false, "The file/path to be used by the executable program for reading its input." }, 3187 { "output-path", eSetVarTypeString, "/dev/stdout", NULL, false, false, "The file/path to be used by the executable program for writing its output." }, 3188 { "error-path", eSetVarTypeString, "/dev/stderr", NULL, false, false, "The file/path to be used by the executable program for writings its error messages." }, 3189 { "plugin", eSetVarTypeEnum, NULL , g_plugins, false, false, "The plugin to be used to run the process." }, 3190 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" }, 3191 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" }, 3192 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL } 3193 }; 3194 3195 3196 3197