MachThreadList.cpp revision 2971e7fc7ede526af9b193f8a9eb10ec4cb2bd62
1//===-- MachThreadList.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//  Created by Greg Clayton on 6/19/07.
11//
12//===----------------------------------------------------------------------===//
13
14#include "MachThreadList.h"
15
16#include <sys/sysctl.h>
17
18#include "DNBLog.h"
19#include "DNBThreadResumeActions.h"
20#include "MachProcess.h"
21
22MachThreadList::MachThreadList() :
23    m_threads(),
24    m_threads_mutex(PTHREAD_MUTEX_RECURSIVE)
25{
26}
27
28MachThreadList::~MachThreadList()
29{
30}
31
32nub_state_t
33MachThreadList::GetState(thread_t tid)
34{
35    MachThreadSP thread_sp (GetThreadByID (tid));
36    if (thread_sp)
37        return thread_sp->GetState();
38    return eStateInvalid;
39}
40
41const char *
42MachThreadList::GetName (thread_t tid)
43{
44    MachThreadSP thread_sp (GetThreadByID (tid));
45    if (thread_sp)
46        return thread_sp->GetName();
47    return NULL;
48}
49
50nub_thread_t
51MachThreadList::SetCurrentThread(thread_t tid)
52{
53    MachThreadSP thread_sp (GetThreadByID (tid));
54    if (thread_sp)
55    {
56        m_current_thread = thread_sp;
57        return tid;
58    }
59    return INVALID_NUB_THREAD;
60}
61
62
63bool
64MachThreadList::GetThreadStoppedReason(nub_thread_t tid, struct DNBThreadStopInfo *stop_info) const
65{
66    MachThreadSP thread_sp (GetThreadByID (tid));
67    if (thread_sp)
68        return thread_sp->GetStopException().GetStopInfo(stop_info);
69    return false;
70}
71
72bool
73MachThreadList::GetIdentifierInfo (nub_thread_t tid, thread_identifier_info_data_t *ident_info)
74{
75    mach_msg_type_number_t count = THREAD_IDENTIFIER_INFO_COUNT;
76    return ::thread_info (tid, THREAD_IDENTIFIER_INFO, (thread_info_t)ident_info, &count) == KERN_SUCCESS;
77}
78
79void
80MachThreadList::DumpThreadStoppedReason (nub_thread_t tid) const
81{
82    MachThreadSP thread_sp (GetThreadByID (tid));
83    if (thread_sp)
84        thread_sp->GetStopException().DumpStopReason();
85}
86
87const char *
88MachThreadList::GetThreadInfo (nub_thread_t tid) const
89{
90    MachThreadSP thread_sp (GetThreadByID (tid));
91    if (thread_sp)
92        return thread_sp->GetBasicInfoAsString();
93    return NULL;
94}
95
96MachThreadSP
97MachThreadList::GetThreadByID (nub_thread_t tid) const
98{
99    PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
100    MachThreadSP thread_sp;
101    const size_t num_threads = m_threads.size();
102    for (size_t idx = 0; idx < num_threads; ++idx)
103    {
104        if (m_threads[idx]->ThreadID() == tid)
105        {
106            thread_sp = m_threads[idx];
107            break;
108        }
109    }
110    return thread_sp;
111}
112
113bool
114MachThreadList::GetRegisterValue ( nub_thread_t tid, uint32_t reg_set_idx, uint32_t reg_idx, DNBRegisterValue *reg_value ) const
115{
116    MachThreadSP thread_sp (GetThreadByID (tid));
117    if (thread_sp)
118        return thread_sp->GetRegisterValue(reg_set_idx, reg_idx, reg_value);
119
120    return false;
121}
122
123bool
124MachThreadList::SetRegisterValue ( nub_thread_t tid, uint32_t reg_set_idx, uint32_t reg_idx, const DNBRegisterValue *reg_value ) const
125{
126    MachThreadSP thread_sp (GetThreadByID (tid));
127    if (thread_sp)
128        return thread_sp->SetRegisterValue(reg_set_idx, reg_idx, reg_value);
129
130    return false;
131}
132
133nub_size_t
134MachThreadList::GetRegisterContext (nub_thread_t tid, void *buf, size_t buf_len)
135{
136    MachThreadSP thread_sp (GetThreadByID (tid));
137    if (thread_sp)
138        return thread_sp->GetRegisterContext (buf, buf_len);
139    return 0;
140}
141
142nub_size_t
143MachThreadList::SetRegisterContext (nub_thread_t tid, const void *buf, size_t buf_len)
144{
145    MachThreadSP thread_sp (GetThreadByID (tid));
146    if (thread_sp)
147        return thread_sp->SetRegisterContext (buf, buf_len);
148    return 0;
149}
150
151nub_size_t
152MachThreadList::NumThreads () const
153{
154    PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
155    return m_threads.size();
156}
157
158nub_thread_t
159MachThreadList::ThreadIDAtIndex (nub_size_t idx) const
160{
161    PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
162    if (idx < m_threads.size())
163        return m_threads[idx]->ThreadID();
164    return INVALID_NUB_THREAD;
165}
166
167nub_thread_t
168MachThreadList::CurrentThreadID ( )
169{
170    MachThreadSP thread_sp;
171    CurrentThread(thread_sp);
172    if (thread_sp.get())
173        return thread_sp->ThreadID();
174    return INVALID_NUB_THREAD;
175}
176
177bool
178MachThreadList::NotifyException(MachException::Data& exc)
179{
180    MachThreadSP thread_sp (GetThreadByID (exc.thread_port));
181    if (thread_sp)
182    {
183        thread_sp->NotifyException(exc);
184        return true;
185    }
186    return false;
187}
188
189void
190MachThreadList::Clear()
191{
192    PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
193    m_threads.clear();
194}
195
196uint32_t
197MachThreadList::UpdateThreadList(MachProcess *process, bool update, MachThreadList::collection *new_threads)
198{
199    // locker will keep a mutex locked until it goes out of scope
200    DNBLogThreadedIf (LOG_THREAD, "MachThreadList::UpdateThreadList (pid = %4.4x, update = %u) process stop count = %u", process->ProcessID(), update, process->StopCount());
201    PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
202
203#if defined (__i386__) || defined (__x86_64__)
204    if (process->StopCount() == 0)
205    {
206        int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, process->ProcessID() };
207        struct kinfo_proc processInfo;
208        size_t bufsize = sizeof(processInfo);
209        bool is_64_bit = false;
210        if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo, &bufsize, NULL, 0) == 0 && bufsize > 0)
211        {
212            if (processInfo.kp_proc.p_flag & P_LP64)
213                is_64_bit = true;
214        }
215        if (is_64_bit)
216            DNBArchProtocol::SetArchitecture(CPU_TYPE_X86_64);
217        else
218            DNBArchProtocol::SetArchitecture(CPU_TYPE_I386);
219    }
220#endif
221
222    if (m_threads.empty() || update)
223    {
224        thread_array_t thread_list = NULL;
225        mach_msg_type_number_t thread_list_count = 0;
226        task_t task = process->Task().TaskPort();
227        DNBError err(::task_threads (task, &thread_list, &thread_list_count), DNBError::MachKernel);
228
229        if (DNBLogCheckLogBit(LOG_THREAD) || err.Fail())
230            err.LogThreaded("::task_threads ( task = 0x%4.4x, thread_list => %p, thread_list_count => %u )", task, thread_list, thread_list_count);
231
232        if (err.Error() == KERN_SUCCESS && thread_list_count > 0)
233        {
234            MachThreadList::collection currThreads;
235            size_t idx;
236            // Iterator through the current thread list and see which threads
237            // we already have in our list (keep them), which ones we don't
238            // (add them), and which ones are not around anymore (remove them).
239            for (idx = 0; idx < thread_list_count; ++idx)
240            {
241                const thread_t tid = thread_list[idx];
242
243                MachThreadSP thread_sp (GetThreadByID (tid));
244                if (thread_sp)
245                {
246                    // Keep the existing thread class
247                    currThreads.push_back(thread_sp);
248                }
249                else
250                {
251                    // We don't have this thread, lets add it.
252                    thread_sp.reset(new MachThread(process, tid));
253
254                    // Add the new thread regardless of its is user ready state...
255                    if (new_threads)
256                        new_threads->push_back(thread_sp);
257
258                    // Make sure the thread is ready to be displayed and shown to users
259                    // before we add this thread to our list...
260                    if (thread_sp->IsUserReady())
261                        currThreads.push_back(thread_sp);
262                }
263            }
264
265            m_threads.swap(currThreads);
266            m_current_thread.reset();
267
268            // Free the vm memory given to us by ::task_threads()
269            vm_size_t thread_list_size = (vm_size_t) (thread_list_count * sizeof (thread_t));
270            ::vm_deallocate (::mach_task_self(),
271                             (vm_address_t)thread_list,
272                             thread_list_size);
273        }
274    }
275    return m_threads.size();
276}
277
278
279void
280MachThreadList::CurrentThread (MachThreadSP& thread_sp)
281{
282    // locker will keep a mutex locked until it goes out of scope
283    PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
284    if (m_current_thread.get() == NULL)
285    {
286        // Figure out which thread is going to be our current thread.
287        // This is currently done by finding the first thread in the list
288        // that has a valid exception.
289        const uint32_t num_threads = m_threads.size();
290        for (uint32_t idx = 0; idx < num_threads; ++idx)
291        {
292            if (m_threads[idx]->GetStopException().IsValid())
293            {
294                m_current_thread = m_threads[idx];
295                break;
296            }
297        }
298    }
299    thread_sp = m_current_thread;
300}
301
302void
303MachThreadList::Dump() const
304{
305    PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
306    const uint32_t num_threads = m_threads.size();
307    for (uint32_t idx = 0; idx < num_threads; ++idx)
308    {
309        m_threads[idx]->Dump(idx);
310    }
311}
312
313
314void
315MachThreadList::ProcessWillResume(MachProcess *process, const DNBThreadResumeActions &thread_actions)
316{
317    PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
318
319    // Update our thread list, because sometimes libdispatch or the kernel
320    // will spawn threads while a task is suspended.
321    MachThreadList::collection new_threads;
322
323    UpdateThreadList(process, true, &new_threads);
324
325    const uint32_t num_threads = m_threads.size();
326    for (uint32_t idx = 0; idx < num_threads; ++idx)
327    {
328        MachThread *thread = m_threads[idx].get();
329
330        const DNBThreadResumeAction *thread_action = thread_actions.GetActionForThread (thread->ThreadID(), true);
331        // There must always be a thread action for every thread.
332        assert (thread_action);
333        thread->ThreadWillResume (thread_action);
334    }
335
336    if (new_threads.size())
337    {
338        for (uint32_t idx = 0, num_new_threads = new_threads.size(); idx < num_new_threads; ++idx)
339        {
340            DNBLogThreadedIf (LOG_THREAD, "MachThreadList::ProcessWillResume (pid = %4.4x) stop-id=%u, resuming newly discovered thread: 0x%4.4x, thread-is-user-ready=%i)",
341                              process->ProcessID(),
342                              process->StopCount(),
343                              new_threads[idx]->ThreadID(),
344                              new_threads[idx]->IsUserReady());
345        }
346    }
347}
348
349uint32_t
350MachThreadList::ProcessDidStop(MachProcess *process)
351{
352    PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
353    // Update our thread list
354    const uint32_t num_threads = UpdateThreadList(process, true);
355    for (uint32_t idx = 0; idx < num_threads; ++idx)
356    {
357        m_threads[idx]->ThreadDidStop();
358    }
359    return num_threads;
360}
361
362//----------------------------------------------------------------------
363// Check each thread in our thread list to see if we should notify our
364// client of the current halt in execution.
365//
366// Breakpoints can have callback functions associated with them than
367// can return true to stop, or false to continue executing the inferior.
368//
369// RETURNS
370//    true if we should stop and notify our clients
371//    false if we should resume our child process and skip notification
372//----------------------------------------------------------------------
373bool
374MachThreadList::ShouldStop(bool &step_more)
375{
376    PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
377    uint32_t should_stop = false;
378    const uint32_t num_threads = m_threads.size();
379    for (uint32_t idx = 0; !should_stop && idx < num_threads; ++idx)
380    {
381        should_stop = m_threads[idx]->ShouldStop(step_more);
382    }
383    return should_stop;
384}
385
386
387void
388MachThreadList::NotifyBreakpointChanged (const DNBBreakpoint *bp)
389{
390    PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
391    const uint32_t num_threads = m_threads.size();
392    for (uint32_t idx = 0; idx < num_threads; ++idx)
393    {
394        m_threads[idx]->NotifyBreakpointChanged(bp);
395    }
396}
397
398
399uint32_t
400MachThreadList::EnableHardwareBreakpoint (const DNBBreakpoint* bp) const
401{
402    if (bp != NULL)
403    {
404        MachThreadSP thread_sp (GetThreadByID (bp->ThreadID()));
405        if (thread_sp)
406            return thread_sp->EnableHardwareBreakpoint(bp);
407    }
408    return INVALID_NUB_HW_INDEX;
409}
410
411bool
412MachThreadList::DisableHardwareBreakpoint (const DNBBreakpoint* bp) const
413{
414    if (bp != NULL)
415    {
416        MachThreadSP thread_sp (GetThreadByID (bp->ThreadID()));
417        if (thread_sp)
418            return thread_sp->DisableHardwareBreakpoint(bp);
419    }
420    return false;
421}
422
423uint32_t
424MachThreadList::EnableHardwareWatchpoint (const DNBBreakpoint* wp) const
425{
426    if (wp != NULL)
427    {
428        MachThreadSP thread_sp (GetThreadByID (wp->ThreadID()));
429        if (thread_sp)
430            return thread_sp->EnableHardwareWatchpoint(wp);
431    }
432    return INVALID_NUB_HW_INDEX;
433}
434
435bool
436MachThreadList::DisableHardwareWatchpoint (const DNBBreakpoint* wp) const
437{
438    if (wp != NULL)
439    {
440        MachThreadSP thread_sp (GetThreadByID (wp->ThreadID()));
441        if (thread_sp)
442            return thread_sp->DisableHardwareWatchpoint(wp);
443    }
444    return false;
445}
446
447uint32_t
448MachThreadList::GetThreadIndexForThreadStoppedWithSignal (const int signo) const
449{
450    PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
451    uint32_t should_stop = false;
452    const uint32_t num_threads = m_threads.size();
453    for (uint32_t idx = 0; !should_stop && idx < num_threads; ++idx)
454    {
455        if (m_threads[idx]->GetStopException().SoftSignal () == signo)
456            return idx;
457    }
458    return UINT32_MAX;
459}
460
461