]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/ProcessPOSIX.cpp
Update LLDB snapshot to upstream r241361
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Plugins / Process / FreeBSD / ProcessPOSIX.cpp
1 //===-- ProcessPOSIX.cpp ----------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 // C Includes
11 #include <errno.h>
12
13 // C++ Includes
14 // Other libraries and framework includes
15 #include "lldb/Breakpoint/BreakpointLocation.h"
16 #include "lldb/Breakpoint/Watchpoint.h"
17 #include "lldb/Core/Module.h"
18 #include "lldb/Core/ModuleSpec.h"
19 #include "lldb/Core/PluginManager.h"
20 #include "lldb/Core/State.h"
21 #include "lldb/Host/FileSpec.h"
22 #include "lldb/Host/Host.h"
23 #include "lldb/Symbol/ObjectFile.h"
24 #include "lldb/Target/DynamicLoader.h"
25 #include "lldb/Target/Platform.h"
26 #include "lldb/Target/Target.h"
27
28 #include "ProcessPOSIX.h"
29 #include "ProcessPOSIXLog.h"
30 #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
31 #include "POSIXThread.h"
32 #include "ProcessMonitor.h"
33
34 #include "lldb/Host/posix/Fcntl.h"
35
36 using namespace lldb;
37 using namespace lldb_private;
38
39 //------------------------------------------------------------------------------
40 // Constructors and destructors.
41
42 ProcessPOSIX::ProcessPOSIX(Target& target, Listener &listener, UnixSignalsSP &unix_signals_sp)
43     : Process(target, listener, unix_signals_sp),
44       m_byte_order(lldb::endian::InlHostByteOrder()),
45       m_monitor(NULL),
46       m_module(NULL),
47       m_message_mutex (Mutex::eMutexTypeRecursive),
48       m_exit_now(false),
49       m_seen_initial_stop()
50 {
51     // FIXME: Putting this code in the ctor and saving the byte order in a
52     // member variable is a hack to avoid const qual issues in GetByteOrder.
53     lldb::ModuleSP module = GetTarget().GetExecutableModule();
54     if (module && module->GetObjectFile())
55         m_byte_order = module->GetObjectFile()->GetByteOrder();
56 }
57
58 ProcessPOSIX::~ProcessPOSIX()
59 {
60     delete m_monitor;
61 }
62
63 //------------------------------------------------------------------------------
64 // Process protocol.
65 void
66 ProcessPOSIX::Finalize()
67 {
68   Process::Finalize();
69
70   if (m_monitor)
71     m_monitor->StopMonitor();
72 }
73
74 bool
75 ProcessPOSIX::CanDebug(Target &target, bool plugin_specified_by_name)
76 {
77     // For now we are just making sure the file exists for a given module
78     ModuleSP exe_module_sp(target.GetExecutableModule());
79     if (exe_module_sp.get())
80         return exe_module_sp->GetFileSpec().Exists();
81     // If there is no executable module, we return true since we might be preparing to attach.
82     return true;
83 }
84
85 Error
86 ProcessPOSIX::DoAttachToProcessWithID (lldb::pid_t pid,  const ProcessAttachInfo &attach_info)
87 {
88     Error error;
89     assert(m_monitor == NULL);
90
91     Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
92     if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
93         log->Printf ("ProcessPOSIX::%s(pid = %" PRIi64 ")", __FUNCTION__, GetID());
94
95     m_monitor = new ProcessMonitor(this, pid, error);
96
97     if (!error.Success())
98         return error;
99
100     PlatformSP platform_sp (m_target.GetPlatform ());
101     assert (platform_sp.get());
102     if (!platform_sp)
103         return error;  // FIXME: Detatch?
104
105     // Find out what we can about this process
106     ProcessInstanceInfo process_info;
107     platform_sp->GetProcessInfo (pid, process_info);
108
109     // Resolve the executable module
110     ModuleSP exe_module_sp;
111     FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
112     ModuleSpec exe_module_spec(process_info.GetExecutableFile(), m_target.GetArchitecture());
113     error = platform_sp->ResolveExecutable(exe_module_spec,
114                                            exe_module_sp,
115                                            executable_search_paths.GetSize() ? &executable_search_paths : NULL);
116     if (!error.Success())
117         return error;
118
119     // Fix the target architecture if necessary
120     const ArchSpec &module_arch = exe_module_sp->GetArchitecture();
121     if (module_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(module_arch))
122         m_target.SetArchitecture(module_arch);
123
124     // Initialize the target module list
125     m_target.SetExecutableModule (exe_module_sp, true);
126
127     SetSTDIOFileDescriptor(m_monitor->GetTerminalFD());
128
129     SetID(pid);
130
131     return error;
132 }
133
134 Error
135 ProcessPOSIX::WillLaunch(Module* module)
136 {
137     Error error;
138     return error;
139 }
140
141 FileSpec
142 ProcessPOSIX::GetFileSpec(const lldb_private::FileAction *file_action,
143                           const FileSpec &default_file_spec,
144                           const FileSpec &dbg_pts_file_spec)
145 {
146     FileSpec file_spec{};
147
148     if (file_action && file_action->GetAction() == FileAction::eFileActionOpen)
149     {
150         file_spec = file_action->GetFileSpec();
151         // By default the stdio paths passed in will be pseudo-terminal
152         // (/dev/pts). If so, convert to using a different default path
153         // instead to redirect I/O to the debugger console. This should
154         // also handle user overrides to /dev/null or a different file.
155         if (!file_spec || file_spec == dbg_pts_file_spec)
156             file_spec = default_file_spec;
157     }
158     return file_spec;
159 }
160
161 Error
162 ProcessPOSIX::DoLaunch (Module *module,
163                         ProcessLaunchInfo &launch_info)
164 {
165     Error error;
166     assert(m_monitor == NULL);
167
168     FileSpec working_dir = launch_info.GetWorkingDirectory();
169     if (working_dir &&
170             (!working_dir.ResolvePath() ||
171              working_dir.GetFileType() != FileSpec::eFileTypeDirectory))
172     {
173         error.SetErrorStringWithFormat("No such file or directory: %s",
174                 working_dir.GetCString());
175         return error;
176     }
177
178     SetPrivateState(eStateLaunching);
179
180     const lldb_private::FileAction *file_action;
181
182     // Default of empty will mean to use existing open file descriptors
183     FileSpec stdin_file_spec{};
184     FileSpec stdout_file_spec{};
185     FileSpec stderr_file_spec{};
186
187     const FileSpec dbg_pts_file_spec{launch_info.GetPTY().GetSlaveName(NULL,0), false};
188
189     file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
190     stdin_file_spec = GetFileSpec(file_action, stdin_file_spec, dbg_pts_file_spec);
191
192     file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
193     stdout_file_spec = GetFileSpec(file_action, stdout_file_spec, dbg_pts_file_spec);
194
195     file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
196     stderr_file_spec = GetFileSpec(file_action, stderr_file_spec, dbg_pts_file_spec);
197
198     m_monitor = new ProcessMonitor(this,
199                                    module,
200                                    launch_info.GetArguments().GetConstArgumentVector(),
201                                    launch_info.GetEnvironmentEntries().GetConstArgumentVector(),
202                                    stdin_file_spec,
203                                    stdout_file_spec,
204                                    stderr_file_spec,
205                                    working_dir,
206                                    launch_info,
207                                    error);
208
209     m_module = module;
210
211     if (!error.Success())
212         return error;
213
214     int terminal = m_monitor->GetTerminalFD();
215     if (terminal >= 0) {
216         // The reader thread will close the file descriptor when done, so we pass it a copy.
217         int stdio = fcntl(terminal, F_DUPFD_CLOEXEC, 0);
218         if (stdio == -1) {
219             error.SetErrorToErrno();
220             return error;
221         }
222         SetSTDIOFileDescriptor(stdio);
223     }
224
225     SetID(m_monitor->GetPID());
226     return error;
227 }
228
229 void
230 ProcessPOSIX::DidLaunch()
231 {
232 }
233
234 Error
235 ProcessPOSIX::DoResume()
236 {
237     StateType state = GetPrivateState();
238
239     assert(state == eStateStopped);
240
241     SetPrivateState(eStateRunning);
242
243     bool did_resume = false;
244
245     Mutex::Locker lock(m_thread_list.GetMutex());
246
247     uint32_t thread_count = m_thread_list.GetSize(false);
248     for (uint32_t i = 0; i < thread_count; ++i)
249     {
250         POSIXThread *thread = static_cast<POSIXThread*>(
251             m_thread_list.GetThreadAtIndex(i, false).get());
252         did_resume = thread->Resume() || did_resume;
253     }
254     assert(did_resume && "Process resume failed!");
255
256     return Error();
257 }
258
259 addr_t
260 ProcessPOSIX::GetImageInfoAddress()
261 {
262     Target *target = &GetTarget();
263     ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
264     Address addr = obj_file->GetImageInfoAddress(target);
265
266     if (addr.IsValid())
267         return addr.GetLoadAddress(target);
268     return LLDB_INVALID_ADDRESS;
269 }
270
271 Error
272 ProcessPOSIX::DoHalt(bool &caused_stop)
273 {
274     Error error;
275
276     if (IsStopped())
277     {
278         caused_stop = false;
279     }
280     else if (kill(GetID(), SIGSTOP))
281     {
282         caused_stop = false;
283         error.SetErrorToErrno();
284     }
285     else
286     {
287         caused_stop = true;
288     }
289     return error;
290 }
291
292 Error
293 ProcessPOSIX::DoSignal(int signal)
294 {
295     Error error;
296
297     if (kill(GetID(), signal))
298         error.SetErrorToErrno();
299
300     return error;
301 }
302
303 Error
304 ProcessPOSIX::DoDestroy()
305 {
306     Error error;
307
308     if (!HasExited())
309     {
310         assert(m_monitor);
311         m_exit_now = true;
312         if (GetID() == LLDB_INVALID_PROCESS_ID)
313         {
314             error.SetErrorString("invalid process id");
315             return error;
316         }
317         if (!m_monitor->Kill())
318         {
319             error.SetErrorToErrno();
320             return error;
321         }
322
323         SetPrivateState(eStateExited);
324     }
325
326     return error;
327 }
328
329 void
330 ProcessPOSIX::DoDidExec()
331 {
332     Target *target = &GetTarget();
333     if (target)
334     {
335         PlatformSP platform_sp (target->GetPlatform());
336         assert (platform_sp.get());
337         if (platform_sp)
338         {
339             ProcessInstanceInfo process_info;
340             platform_sp->GetProcessInfo(GetID(), process_info);
341             ModuleSP exe_module_sp;
342             ModuleSpec exe_module_spec(process_info.GetExecutableFile(), target->GetArchitecture());
343             FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
344             Error error = platform_sp->ResolveExecutable(exe_module_spec,
345                                                          exe_module_sp,
346                                                          executable_search_paths.GetSize() ? &executable_search_paths : NULL);
347             if (!error.Success())
348                 return;
349             target->SetExecutableModule(exe_module_sp, true);
350         }
351     }
352 }
353
354 void
355 ProcessPOSIX::SendMessage(const ProcessMessage &message)
356 {
357     Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
358
359     Mutex::Locker lock(m_message_mutex);
360
361     Mutex::Locker thread_lock(m_thread_list.GetMutex());
362
363     POSIXThread *thread = static_cast<POSIXThread*>(
364         m_thread_list.FindThreadByID(message.GetTID(), false).get());
365
366     switch (message.GetKind())
367     {
368     case ProcessMessage::eInvalidMessage:
369         return;
370
371     case ProcessMessage::eAttachMessage:
372         SetPrivateState(eStateStopped);
373         return;
374
375     case ProcessMessage::eLimboMessage:
376         assert(thread);
377         thread->SetState(eStateStopped);
378         if (message.GetTID() == GetID())
379         {
380             m_exit_status = message.GetExitStatus();
381             if (m_exit_now)
382             {
383                 SetPrivateState(eStateExited);
384                 m_monitor->Detach(GetID());
385             }
386             else
387             {
388                 SetPrivateState(eStateStopped);
389             }
390         }
391         else
392         {
393             SetPrivateState(eStateStopped);
394         }
395         break;
396
397     case ProcessMessage::eExitMessage:
398         if (thread != nullptr)
399             thread->SetState(eStateExited);
400         else
401         {
402             if (log)
403                 log->Warning ("ProcessPOSIX::%s eExitMessage for TID %" PRIu64 " failed to find a thread to mark as eStateExited, ignoring", __FUNCTION__, message.GetTID ());
404         }
405
406         // FIXME: I'm not sure we need to do this.
407         if (message.GetTID() == GetID())
408         {
409             SetExitStatus(message.GetExitStatus(), NULL);
410         }
411         else if (!IsAThreadRunning())
412             SetPrivateState(eStateStopped);
413         break;
414
415     case ProcessMessage::eSignalMessage:
416     case ProcessMessage::eSignalDeliveredMessage:
417         if (message.GetSignal() == SIGSTOP &&
418             AddThreadForInitialStopIfNeeded(message.GetTID()))
419             return;
420         // Intentional fall-through
421
422     case ProcessMessage::eBreakpointMessage:
423     case ProcessMessage::eTraceMessage:
424     case ProcessMessage::eWatchpointMessage:
425     case ProcessMessage::eCrashMessage:
426         assert(thread);
427         thread->SetState(eStateStopped);
428         SetPrivateState(eStateStopped);
429         break;
430
431     case ProcessMessage::eNewThreadMessage:
432     {
433         lldb::tid_t  new_tid = message.GetChildTID();
434         if (WaitingForInitialStop(new_tid))
435         {
436             m_monitor->WaitForInitialTIDStop(new_tid);
437         }
438         assert(thread);
439         thread->SetState(eStateStopped);
440         SetPrivateState(eStateStopped);
441         break;
442     }
443
444     case ProcessMessage::eExecMessage:
445     {
446         assert(thread);
447         thread->SetState(eStateStopped);
448         SetPrivateState(eStateStopped);
449         break;
450     }
451     }
452
453
454     m_message_queue.push(message);
455 }
456
457 bool
458 ProcessPOSIX::AddThreadForInitialStopIfNeeded(lldb::tid_t stop_tid)
459 {
460     bool added_to_set = false;
461     ThreadStopSet::iterator it = m_seen_initial_stop.find(stop_tid);
462     if (it == m_seen_initial_stop.end())
463     {
464         m_seen_initial_stop.insert(stop_tid);
465         added_to_set = true;
466     }
467     return added_to_set;
468 }
469
470 bool
471 ProcessPOSIX::WaitingForInitialStop(lldb::tid_t stop_tid)
472 {
473     return (m_seen_initial_stop.find(stop_tid) == m_seen_initial_stop.end());
474 }
475
476 POSIXThread *
477 ProcessPOSIX::CreateNewPOSIXThread(lldb_private::Process &process, lldb::tid_t tid)
478 {
479     return new POSIXThread(process, tid);
480 }
481
482 void
483 ProcessPOSIX::RefreshStateAfterStop()
484 {
485     Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
486     if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
487         log->Printf ("ProcessPOSIX::%s(), message_queue size = %d", __FUNCTION__, (int)m_message_queue.size());
488
489     Mutex::Locker lock(m_message_mutex);
490
491     // This method used to only handle one message.  Changing it to loop allows
492     // it to handle the case where we hit a breakpoint while handling a different
493     // breakpoint.
494     while (!m_message_queue.empty())
495     {
496         ProcessMessage &message = m_message_queue.front();
497
498         // Resolve the thread this message corresponds to and pass it along.
499         lldb::tid_t tid = message.GetTID();
500         if (log)
501             log->Printf ("ProcessPOSIX::%s(), message_queue size = %d, pid = %" PRIi64, __FUNCTION__, (int)m_message_queue.size(), tid);
502
503         if (message.GetKind() == ProcessMessage::eNewThreadMessage)
504         {
505             if (log)
506                 log->Printf ("ProcessPOSIX::%s() adding thread, tid = %" PRIi64, __FUNCTION__, message.GetChildTID());
507             lldb::tid_t child_tid = message.GetChildTID();
508             ThreadSP thread_sp;
509             thread_sp.reset(CreateNewPOSIXThread(*this, child_tid));
510
511             Mutex::Locker lock(m_thread_list.GetMutex());
512
513             m_thread_list.AddThread(thread_sp);
514         }
515
516         m_thread_list.RefreshStateAfterStop();
517
518         POSIXThread *thread = static_cast<POSIXThread*>(
519             GetThreadList().FindThreadByID(tid, false).get());
520         if (thread)
521             thread->Notify(message);
522
523         if (message.GetKind() == ProcessMessage::eExitMessage)
524         {
525             // FIXME: We should tell the user about this, but the limbo message is probably better for that.
526             if (log)
527                 log->Printf ("ProcessPOSIX::%s() removing thread, tid = %" PRIi64, __FUNCTION__, tid);
528
529             Mutex::Locker lock(m_thread_list.GetMutex());
530
531             ThreadSP thread_sp = m_thread_list.RemoveThreadByID(tid, false);
532             thread_sp.reset();
533             m_seen_initial_stop.erase(tid);
534         }
535
536         m_message_queue.pop();
537     }
538 }
539
540 bool
541 ProcessPOSIX::IsAlive()
542 {
543     StateType state = GetPrivateState();
544     return state != eStateDetached
545         && state != eStateExited
546         && state != eStateInvalid
547         && state != eStateUnloaded;
548 }
549
550 size_t
551 ProcessPOSIX::DoReadMemory(addr_t vm_addr,
552                            void *buf, size_t size, Error &error)
553 {
554     assert(m_monitor);
555     return m_monitor->ReadMemory(vm_addr, buf, size, error);
556 }
557
558 size_t
559 ProcessPOSIX::DoWriteMemory(addr_t vm_addr, const void *buf, size_t size,
560                             Error &error)
561 {
562     assert(m_monitor);
563     return m_monitor->WriteMemory(vm_addr, buf, size, error);
564 }
565
566 addr_t
567 ProcessPOSIX::DoAllocateMemory(size_t size, uint32_t permissions,
568                                Error &error)
569 {
570     addr_t allocated_addr = LLDB_INVALID_ADDRESS;
571
572     unsigned prot = 0;
573     if (permissions & lldb::ePermissionsReadable)
574         prot |= eMmapProtRead;
575     if (permissions & lldb::ePermissionsWritable)
576         prot |= eMmapProtWrite;
577     if (permissions & lldb::ePermissionsExecutable)
578         prot |= eMmapProtExec;
579
580     if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
581                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
582         m_addr_to_mmap_size[allocated_addr] = size;
583         error.Clear();
584     } else {
585         allocated_addr = LLDB_INVALID_ADDRESS;
586         error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
587     }
588
589     return allocated_addr;
590 }
591
592 Error
593 ProcessPOSIX::DoDeallocateMemory(lldb::addr_t addr)
594 {
595     Error error;
596     MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
597     if (pos != m_addr_to_mmap_size.end() &&
598         InferiorCallMunmap(this, addr, pos->second))
599         m_addr_to_mmap_size.erase (pos);
600     else
601         error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
602
603     return error;
604 }
605
606 size_t
607 ProcessPOSIX::GetSoftwareBreakpointTrapOpcode(BreakpointSite* bp_site)
608 {
609     static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xD4 };
610     static const uint8_t g_i386_opcode[] = { 0xCC };
611
612     ArchSpec arch = GetTarget().GetArchitecture();
613     const uint8_t *opcode = NULL;
614     size_t opcode_size = 0;
615
616     switch (arch.GetMachine())
617     {
618     default:
619         assert(false && "CPU type not supported!");
620         break;
621
622     case llvm::Triple::arm:
623         {
624             // The ARM reference recommends the use of 0xe7fddefe and 0xdefe
625             // but the linux kernel does otherwise.
626             static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
627             static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
628
629             lldb::BreakpointLocationSP bp_loc_sp (bp_site->GetOwnerAtIndex (0));
630             AddressClass addr_class = eAddressClassUnknown;
631
632             if (bp_loc_sp)
633                 addr_class = bp_loc_sp->GetAddress ().GetAddressClass ();
634
635             if (addr_class == eAddressClassCodeAlternateISA
636                 || (addr_class == eAddressClassUnknown
637                     && bp_loc_sp->GetAddress().GetOffset() & 1))
638             {
639                 opcode = g_thumb_breakpoint_opcode;
640                 opcode_size = sizeof(g_thumb_breakpoint_opcode);
641             }
642             else
643             {
644                 opcode = g_arm_breakpoint_opcode;
645                 opcode_size = sizeof(g_arm_breakpoint_opcode);
646             }
647         }
648         break;
649     case llvm::Triple::aarch64:
650         opcode = g_aarch64_opcode;
651         opcode_size = sizeof(g_aarch64_opcode);
652         break;
653
654     case llvm::Triple::x86:
655     case llvm::Triple::x86_64:
656         opcode = g_i386_opcode;
657         opcode_size = sizeof(g_i386_opcode);
658         break;
659     }
660
661     bp_site->SetTrapOpcode(opcode, opcode_size);
662     return opcode_size;
663 }
664
665 Error
666 ProcessPOSIX::EnableBreakpointSite(BreakpointSite *bp_site)
667 {
668     return EnableSoftwareBreakpoint(bp_site);
669 }
670
671 Error
672 ProcessPOSIX::DisableBreakpointSite(BreakpointSite *bp_site)
673 {
674     return DisableSoftwareBreakpoint(bp_site);
675 }
676
677 Error
678 ProcessPOSIX::EnableWatchpoint(Watchpoint *wp, bool notify)
679 {
680     Error error;
681     if (wp)
682     {
683         user_id_t watchID = wp->GetID();
684         addr_t addr = wp->GetLoadAddress();
685         Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
686         if (log)
687             log->Printf ("ProcessPOSIX::EnableWatchpoint(watchID = %" PRIu64 ")",
688                          watchID);
689         if (wp->IsEnabled())
690         {
691             if (log)
692                 log->Printf("ProcessPOSIX::EnableWatchpoint(watchID = %" PRIu64
693                             ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
694                             watchID, (uint64_t)addr);
695             return error;
696         }
697
698         // Try to find a vacant watchpoint slot in the inferiors' main thread
699         uint32_t wp_hw_index = LLDB_INVALID_INDEX32;
700         Mutex::Locker lock(m_thread_list.GetMutex());
701         POSIXThread *thread = static_cast<POSIXThread*>(
702                                m_thread_list.GetThreadAtIndex(0, false).get());
703
704         if (thread)
705             wp_hw_index = thread->FindVacantWatchpointIndex();
706
707         if (wp_hw_index == LLDB_INVALID_INDEX32)
708         {
709             error.SetErrorString("Setting hardware watchpoint failed.");
710         }
711         else
712         {
713             wp->SetHardwareIndex(wp_hw_index);
714             bool wp_enabled = true;
715             uint32_t thread_count = m_thread_list.GetSize(false);
716             for (uint32_t i = 0; i < thread_count; ++i)
717             {
718                 thread = static_cast<POSIXThread*>(
719                          m_thread_list.GetThreadAtIndex(i, false).get());
720                 if (thread)
721                     wp_enabled &= thread->EnableHardwareWatchpoint(wp);
722                 else
723                     wp_enabled = false;
724             }
725             if (wp_enabled)
726             {
727                 wp->SetEnabled(true, notify);
728                 return error;
729             }
730             else
731             {
732                 // Watchpoint enabling failed on at least one
733                 // of the threads so roll back all of them
734                 DisableWatchpoint(wp, false);
735                 error.SetErrorString("Setting hardware watchpoint failed");
736             }
737         }
738     }
739     else
740         error.SetErrorString("Watchpoint argument was NULL.");
741     return error;
742 }
743
744 Error
745 ProcessPOSIX::DisableWatchpoint(Watchpoint *wp, bool notify)
746 {
747     Error error;
748     if (wp)
749     {
750         user_id_t watchID = wp->GetID();
751         addr_t addr = wp->GetLoadAddress();
752         Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
753         if (log)
754             log->Printf("ProcessPOSIX::DisableWatchpoint(watchID = %" PRIu64 ")",
755                         watchID);
756         if (!wp->IsEnabled())
757         {
758             if (log)
759                 log->Printf("ProcessPOSIX::DisableWatchpoint(watchID = %" PRIu64
760                             ") addr = 0x%8.8" PRIx64 ": watchpoint already disabled.",
761                             watchID, (uint64_t)addr);
762             // This is needed (for now) to keep watchpoints disabled correctly
763             wp->SetEnabled(false, notify);
764             return error;
765         }
766
767         if (wp->IsHardware())
768         {
769             bool wp_disabled = true;
770             Mutex::Locker lock(m_thread_list.GetMutex());
771             uint32_t thread_count = m_thread_list.GetSize(false);
772             for (uint32_t i = 0; i < thread_count; ++i)
773             {
774                 POSIXThread *thread = static_cast<POSIXThread*>(
775                                       m_thread_list.GetThreadAtIndex(i, false).get());
776                 if (thread)
777                     wp_disabled &= thread->DisableHardwareWatchpoint(wp);
778                 else
779                     wp_disabled = false;
780             }
781             if (wp_disabled)
782             {
783                 wp->SetHardwareIndex(LLDB_INVALID_INDEX32);
784                 wp->SetEnabled(false, notify);
785                 return error;
786             }
787             else
788                 error.SetErrorString("Disabling hardware watchpoint failed");
789         }
790     }
791     else
792         error.SetErrorString("Watchpoint argument was NULL.");
793     return error;
794 }
795
796 Error
797 ProcessPOSIX::GetWatchpointSupportInfo(uint32_t &num)
798 {
799     Error error;
800     Mutex::Locker lock(m_thread_list.GetMutex());
801     POSIXThread *thread = static_cast<POSIXThread*>(
802                           m_thread_list.GetThreadAtIndex(0, false).get());
803     if (thread)
804         num = thread->NumSupportedHardwareWatchpoints();
805     else
806         error.SetErrorString("Process does not exist.");
807     return error;
808 }
809
810 Error
811 ProcessPOSIX::GetWatchpointSupportInfo(uint32_t &num, bool &after)
812 {
813     Error error = GetWatchpointSupportInfo(num);
814     // Watchpoints trigger and halt the inferior after
815     // the corresponding instruction has been executed.
816     after = true;
817     return error;
818 }
819
820 uint32_t
821 ProcessPOSIX::UpdateThreadListIfNeeded()
822 {
823     Mutex::Locker lock(m_thread_list.GetMutex());
824     // Do not allow recursive updates.
825     return m_thread_list.GetSize(false);
826 }
827
828 bool
829 ProcessPOSIX::UpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list)
830 {
831     Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_THREAD));
832     if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
833         log->Printf ("ProcessPOSIX::%s() (pid = %" PRIi64 ")", __FUNCTION__, GetID());
834
835     bool has_updated = false;
836     // Update the process thread list with this new thread.
837     // FIXME: We should be using tid, not pid.
838     assert(m_monitor);
839     ThreadSP thread_sp (old_thread_list.FindThreadByID (GetID(), false));
840     if (!thread_sp) {
841         thread_sp.reset(CreateNewPOSIXThread(*this, GetID()));
842         has_updated = true;
843     }
844
845     if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
846         log->Printf ("ProcessPOSIX::%s() updated pid = %" PRIi64, __FUNCTION__, GetID());
847     new_thread_list.AddThread(thread_sp);
848
849     return has_updated; // the list has been updated
850 }
851
852 ByteOrder
853 ProcessPOSIX::GetByteOrder() const
854 {
855     // FIXME: We should be able to extract this value directly.  See comment in
856     // ProcessPOSIX().
857     return m_byte_order;
858 }
859
860 size_t
861 ProcessPOSIX::PutSTDIN(const char *buf, size_t len, Error &error)
862 {
863     ssize_t status;
864     if ((status = write(m_monitor->GetTerminalFD(), buf, len)) < 0) 
865     {
866         error.SetErrorToErrno();
867         return 0;
868     }
869     return status;
870 }
871
872 //------------------------------------------------------------------------------
873 // Utility functions.
874
875 bool
876 ProcessPOSIX::HasExited()
877 {
878     switch (GetPrivateState())
879     {
880     default:
881         break;
882
883     case eStateDetached:
884     case eStateExited:
885         return true;
886     }
887
888     return false;
889 }
890
891 bool
892 ProcessPOSIX::IsStopped()
893 {
894     switch (GetPrivateState())
895     {
896     default:
897         break;
898
899     case eStateStopped:
900     case eStateCrashed:
901     case eStateSuspended:
902         return true;
903     }
904
905     return false;
906 }
907
908 bool
909 ProcessPOSIX::IsAThreadRunning()
910 {
911     bool is_running = false;
912     Mutex::Locker lock(m_thread_list.GetMutex());
913     uint32_t thread_count = m_thread_list.GetSize(false);
914     for (uint32_t i = 0; i < thread_count; ++i)
915     {
916         POSIXThread *thread = static_cast<POSIXThread*>(
917             m_thread_list.GetThreadAtIndex(i, false).get());
918         StateType thread_state = thread->GetState();
919         if (thread_state == eStateRunning || thread_state == eStateStepping)
920         {
921             is_running = true;
922             break;
923         }
924     }
925     return is_running;
926 }
927
928 const DataBufferSP
929 ProcessPOSIX::GetAuxvData ()
930 {
931     // If we're the local platform, we can ask the host for auxv data.
932     PlatformSP platform_sp = m_target.GetPlatform ();
933     if (platform_sp && platform_sp->IsHost ())
934         return lldb_private::Host::GetAuxvData(this);
935
936     // Somewhat unexpected - the process is not running locally or we don't have a platform.
937     assert (false && "no platform or not the host - how did we get here with ProcessPOSIX?");
938     return DataBufferSP ();
939 }