MachTask.cpp revision e45c499d61f372cc93abdacf3dbfa9466c412066
1//===-- MachTask.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//
11//  MachTask.cpp
12//  debugserver
13//
14//  Created by Greg Clayton on 12/5/08.
15//
16//===----------------------------------------------------------------------===//
17
18#include "MachTask.h"
19
20// C Includes
21
22#include <mach-o/dyld_images.h>
23#include <mach/mach_vm.h>
24
25// C++ Includes
26#include <sstream>
27
28// Other libraries and framework includes
29// Project includes
30#include "CFUtils.h"
31#include "DNB.h"
32#include "DNBError.h"
33#include "DNBLog.h"
34#include "MachProcess.h"
35#include "DNBDataRef.h"
36#include "stack_logging.h"
37
38#ifdef WITH_SPRINGBOARD
39
40#include <CoreFoundation/CoreFoundation.h>
41#include <SpringBoardServices/SpringBoardServer.h>
42#include <SpringBoardServices/SBSWatchdogAssertion.h>
43
44#endif
45
46//----------------------------------------------------------------------
47// MachTask constructor
48//----------------------------------------------------------------------
49MachTask::MachTask(MachProcess *process) :
50    m_process (process),
51    m_task (TASK_NULL),
52    m_vm_memory (),
53    m_exception_thread (0),
54    m_exception_port (MACH_PORT_NULL)
55{
56    memset(&m_exc_port_info, 0, sizeof(m_exc_port_info));
57
58}
59
60//----------------------------------------------------------------------
61// Destructor
62//----------------------------------------------------------------------
63MachTask::~MachTask()
64{
65    Clear();
66}
67
68
69//----------------------------------------------------------------------
70// MachTask::Suspend
71//----------------------------------------------------------------------
72kern_return_t
73MachTask::Suspend()
74{
75    DNBError err;
76    task_t task = TaskPort();
77    err = ::task_suspend (task);
78    if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
79        err.LogThreaded("::task_suspend ( target_task = 0x%4.4x )", task);
80    return err.Error();
81}
82
83
84//----------------------------------------------------------------------
85// MachTask::Resume
86//----------------------------------------------------------------------
87kern_return_t
88MachTask::Resume()
89{
90    struct task_basic_info task_info;
91    task_t task = TaskPort();
92    if (task == TASK_NULL)
93        return KERN_INVALID_ARGUMENT;
94
95    DNBError err;
96    err = BasicInfo(task, &task_info);
97
98    if (err.Success())
99    {
100        // task_resume isn't counted like task_suspend calls are, are, so if the
101        // task is not suspended, don't try and resume it since it is already
102        // running
103        if (task_info.suspend_count > 0)
104        {
105            err = ::task_resume (task);
106            if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
107                err.LogThreaded("::task_resume ( target_task = 0x%4.4x )", task);
108        }
109    }
110    return err.Error();
111}
112
113//----------------------------------------------------------------------
114// MachTask::ExceptionPort
115//----------------------------------------------------------------------
116mach_port_t
117MachTask::ExceptionPort() const
118{
119    return m_exception_port;
120}
121
122//----------------------------------------------------------------------
123// MachTask::ExceptionPortIsValid
124//----------------------------------------------------------------------
125bool
126MachTask::ExceptionPortIsValid() const
127{
128    return MACH_PORT_VALID(m_exception_port);
129}
130
131
132//----------------------------------------------------------------------
133// MachTask::Clear
134//----------------------------------------------------------------------
135void
136MachTask::Clear()
137{
138    // Do any cleanup needed for this task
139    m_task = TASK_NULL;
140    m_exception_thread = 0;
141    m_exception_port = MACH_PORT_NULL;
142
143}
144
145
146//----------------------------------------------------------------------
147// MachTask::SaveExceptionPortInfo
148//----------------------------------------------------------------------
149kern_return_t
150MachTask::SaveExceptionPortInfo()
151{
152    return m_exc_port_info.Save(TaskPort());
153}
154
155//----------------------------------------------------------------------
156// MachTask::RestoreExceptionPortInfo
157//----------------------------------------------------------------------
158kern_return_t
159MachTask::RestoreExceptionPortInfo()
160{
161    return m_exc_port_info.Restore(TaskPort());
162}
163
164
165//----------------------------------------------------------------------
166// MachTask::ReadMemory
167//----------------------------------------------------------------------
168nub_size_t
169MachTask::ReadMemory (nub_addr_t addr, nub_size_t size, void *buf)
170{
171    nub_size_t n = 0;
172    task_t task = TaskPort();
173    if (task != TASK_NULL)
174    {
175        n = m_vm_memory.Read(task, addr, buf, size);
176
177        DNBLogThreadedIf(LOG_MEMORY, "MachTask::ReadMemory ( addr = 0x%8.8llx, size = %llu, buf = %p) => %llu bytes read", (uint64_t)addr, (uint64_t)size, buf, (uint64_t)n);
178        if (DNBLogCheckLogBit(LOG_MEMORY_DATA_LONG) || (DNBLogCheckLogBit(LOG_MEMORY_DATA_SHORT) && size <= 8))
179        {
180            DNBDataRef data((uint8_t*)buf, n, false);
181            data.Dump(0, n, addr, DNBDataRef::TypeUInt8, 16);
182        }
183    }
184    return n;
185}
186
187
188//----------------------------------------------------------------------
189// MachTask::WriteMemory
190//----------------------------------------------------------------------
191nub_size_t
192MachTask::WriteMemory (nub_addr_t addr, nub_size_t size, const void *buf)
193{
194    nub_size_t n = 0;
195    task_t task = TaskPort();
196    if (task != TASK_NULL)
197    {
198        n = m_vm_memory.Write(task, addr, buf, size);
199        DNBLogThreadedIf(LOG_MEMORY, "MachTask::WriteMemory ( addr = 0x%8.8llx, size = %llu, buf = %p) => %llu bytes written", (uint64_t)addr, (uint64_t)size, buf, (uint64_t)n);
200        if (DNBLogCheckLogBit(LOG_MEMORY_DATA_LONG) || (DNBLogCheckLogBit(LOG_MEMORY_DATA_SHORT) && size <= 8))
201        {
202            DNBDataRef data((uint8_t*)buf, n, false);
203            data.Dump(0, n, addr, DNBDataRef::TypeUInt8, 16);
204        }
205    }
206    return n;
207}
208
209//----------------------------------------------------------------------
210// MachTask::MemoryRegionInfo
211//----------------------------------------------------------------------
212int
213MachTask::GetMemoryRegionInfo (nub_addr_t addr, DNBRegionInfo *region_info)
214{
215    task_t task = TaskPort();
216    if (task == TASK_NULL)
217        return -1;
218
219    int ret = m_vm_memory.GetMemoryRegionInfo(task, addr, region_info);
220    DNBLogThreadedIf(LOG_MEMORY, "MachTask::MemoryRegionInfo ( addr = 0x%8.8llx ) => %i  (start = 0x%8.8llx, size = 0x%8.8llx, permissions = %u)",
221                     (uint64_t)addr,
222                     ret,
223                     (uint64_t)region_info->addr,
224                     (uint64_t)region_info->size,
225                     region_info->permissions);
226    return ret;
227}
228
229#define TIME_VALUE_TO_TIMEVAL(a, r) do {        \
230(r)->tv_sec = (a)->seconds;                     \
231(r)->tv_usec = (a)->microseconds;               \
232} while (0)
233
234// We should consider moving this into each MacThread.
235static void update_used_time(task_t task, int &num_threads, uint64_t **threads_id, uint64_t **threads_used_usec, struct timeval &current_used_time)
236{
237    kern_return_t kr;
238    thread_act_array_t threads;
239    mach_msg_type_number_t tcnt;
240
241    kr = task_threads(task, &threads, &tcnt);
242    if (kr != KERN_SUCCESS)
243        return;
244
245    num_threads = tcnt;
246    *threads_id = (uint64_t *)malloc(num_threads * sizeof(uint64_t));
247    *threads_used_usec = (uint64_t *)malloc(num_threads * sizeof(uint64_t));
248
249    for (int i = 0; i < tcnt; i++) {
250        thread_identifier_info_data_t identifier_info;
251        mach_msg_type_number_t count = THREAD_IDENTIFIER_INFO_COUNT;
252        kr = thread_info(threads[i], THREAD_IDENTIFIER_INFO, (thread_info_t)&identifier_info, &count);
253        if (kr != KERN_SUCCESS) continue;
254
255        thread_basic_info_data_t basic_info;
256        count = THREAD_BASIC_INFO_COUNT;
257        kr = thread_info(threads[i], THREAD_BASIC_INFO, (thread_info_t)&basic_info, &count);
258        if (kr != KERN_SUCCESS) continue;
259
260        if ((basic_info.flags & TH_FLAGS_IDLE) == 0) {
261            (*threads_id)[i] = identifier_info.thread_id;
262
263            struct timeval tv;
264            struct timeval thread_tv;
265            TIME_VALUE_TO_TIMEVAL(&basic_info.user_time, &tv);
266            TIME_VALUE_TO_TIMEVAL(&basic_info.user_time, &thread_tv);
267            timeradd(&current_used_time, &tv, &current_used_time);
268            TIME_VALUE_TO_TIMEVAL(&basic_info.system_time, &tv);
269            timeradd(&thread_tv, &tv, &thread_tv);
270            timeradd(&current_used_time, &tv, &current_used_time);
271            uint64_t used_usec = thread_tv.tv_sec * 1000000ULL + thread_tv.tv_usec;
272            (*threads_used_usec)[i] = used_usec;
273        }
274
275        kr = mach_port_deallocate(mach_task_self(), threads[i]);
276    }
277    kr = mach_vm_deallocate(mach_task_self(), (mach_vm_address_t)(uintptr_t)threads, tcnt * sizeof(*threads));
278}
279
280const char *
281MachTask::GetProfileDataAsCString ()
282{
283    task_t task = TaskPort();
284    if (task == TASK_NULL)
285        return NULL;
286
287    struct task_basic_info task_info;
288    DNBError err;
289    err = BasicInfo(task, &task_info);
290
291    if (!err.Success())
292        return NULL;
293
294    uint64_t elapsed_usec = 0;
295    uint64_t task_used_usec = 0;
296    int num_threads = 0;
297    uint64_t *threads_used_usec = NULL;
298    uint64_t *threads_id = NULL;
299
300    // Get current used time.
301    struct timeval current_used_time;
302    struct timeval tv;
303    TIME_VALUE_TO_TIMEVAL(&task_info.user_time, &current_used_time);
304    TIME_VALUE_TO_TIMEVAL(&task_info.system_time, &tv);
305    timeradd(&current_used_time, &tv, &current_used_time);
306    task_used_usec = current_used_time.tv_sec * 1000000ULL + current_used_time.tv_usec;
307    update_used_time(task, num_threads, &threads_id, &threads_used_usec, current_used_time);
308
309    struct timeval current_elapsed_time;
310    int res = gettimeofday(&current_elapsed_time, NULL);
311    if (res == 0)
312    {
313        elapsed_usec = current_elapsed_time.tv_sec * 1000000ULL + current_elapsed_time.tv_usec;
314    }
315
316    struct vm_statistics vm_stats;
317    uint64_t physical_memory;
318    mach_vm_size_t rprvt = 0;
319    mach_vm_size_t rsize = 0;
320    mach_vm_size_t vprvt = 0;
321    mach_vm_size_t vsize = 0;
322    mach_vm_size_t dirty_size = 0;
323    if (m_vm_memory.GetMemoryProfile(task, task_info, m_process->GetCPUType(), m_process->ProcessID(), vm_stats, physical_memory, rprvt, rsize, vprvt, vsize, dirty_size))
324    {
325        std::ostringstream profile_data_stream;
326
327        profile_data_stream << "elapsed_usec:" << elapsed_usec << ';';
328        profile_data_stream << "task_used_usec:" << task_used_usec << ';';
329
330        profile_data_stream << "threads_info:" << num_threads;
331        for (int i=0; i<num_threads; i++) {
332            profile_data_stream << ',' << threads_id[i];
333            profile_data_stream << ',' << threads_used_usec[i];
334        }
335        profile_data_stream << ';';
336
337        profile_data_stream << "wired:" << vm_stats.wire_count * vm_page_size << ';';
338        profile_data_stream << "active:" << vm_stats.active_count * vm_page_size << ';';
339        profile_data_stream << "inactive:" << vm_stats.inactive_count * vm_page_size << ';';
340        uint64_t total_used_count = vm_stats.wire_count + vm_stats.inactive_count + vm_stats.active_count;
341        profile_data_stream << "used:" << total_used_count * vm_page_size << ';';
342        profile_data_stream << "free:" << vm_stats.free_count * vm_page_size << ';';
343        profile_data_stream << "total:" << physical_memory << ';';
344
345        profile_data_stream << "rprvt:" << rprvt << ';';
346        profile_data_stream << "rsize:" << rsize << ';';
347        profile_data_stream << "vprvt:" << vprvt << ';';
348        profile_data_stream << "vsize:" << vsize << ';';
349        profile_data_stream << "dirty:" << dirty_size << ';';
350        profile_data_stream << "$";
351
352        m_profile_data = profile_data_stream.str();
353    }
354    else
355    {
356        m_profile_data.clear();
357    }
358
359    free(threads_id);
360    free(threads_used_usec);
361
362    return m_profile_data.c_str();
363}
364
365
366//----------------------------------------------------------------------
367// MachTask::TaskPortForProcessID
368//----------------------------------------------------------------------
369task_t
370MachTask::TaskPortForProcessID (DNBError &err)
371{
372    if (m_task == TASK_NULL && m_process != NULL)
373        m_task = MachTask::TaskPortForProcessID(m_process->ProcessID(), err);
374    return m_task;
375}
376
377//----------------------------------------------------------------------
378// MachTask::TaskPortForProcessID
379//----------------------------------------------------------------------
380task_t
381MachTask::TaskPortForProcessID (pid_t pid, DNBError &err, uint32_t num_retries, uint32_t usec_interval)
382{
383    if (pid != INVALID_NUB_PROCESS)
384    {
385        DNBError err;
386        mach_port_t task_self = mach_task_self ();
387        task_t task = TASK_NULL;
388        for (uint32_t i=0; i<num_retries; i++)
389        {
390            err = ::task_for_pid ( task_self, pid, &task);
391
392            if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
393            {
394                char str[1024];
395                ::snprintf (str,
396                            sizeof(str),
397                            "::task_for_pid ( target_tport = 0x%4.4x, pid = %d, &task ) => err = 0x%8.8x (%s)",
398                            task_self,
399                            pid,
400                            err.Error(),
401                            err.AsString() ? err.AsString() : "success");
402                if (err.Fail())
403                    err.SetErrorString(str);
404                err.LogThreaded(str);
405            }
406
407            if (err.Success())
408                return task;
409
410            // Sleep a bit and try again
411            ::usleep (usec_interval);
412        }
413    }
414    return TASK_NULL;
415}
416
417
418//----------------------------------------------------------------------
419// MachTask::BasicInfo
420//----------------------------------------------------------------------
421kern_return_t
422MachTask::BasicInfo(struct task_basic_info *info)
423{
424    return BasicInfo (TaskPort(), info);
425}
426
427//----------------------------------------------------------------------
428// MachTask::BasicInfo
429//----------------------------------------------------------------------
430kern_return_t
431MachTask::BasicInfo(task_t task, struct task_basic_info *info)
432{
433    if (info == NULL)
434        return KERN_INVALID_ARGUMENT;
435
436    DNBError err;
437    mach_msg_type_number_t count = TASK_BASIC_INFO_COUNT;
438    err = ::task_info (task, TASK_BASIC_INFO, (task_info_t)info, &count);
439    const bool log_process = DNBLogCheckLogBit(LOG_TASK);
440    if (log_process || err.Fail())
441        err.LogThreaded("::task_info ( target_task = 0x%4.4x, flavor = TASK_BASIC_INFO, task_info_out => %p, task_info_outCnt => %u )", task, info, count);
442    if (DNBLogCheckLogBit(LOG_TASK) && DNBLogCheckLogBit(LOG_VERBOSE) && err.Success())
443    {
444        float user = (float)info->user_time.seconds + (float)info->user_time.microseconds / 1000000.0f;
445        float system = (float)info->user_time.seconds + (float)info->user_time.microseconds / 1000000.0f;
446        DNBLogThreaded ("task_basic_info = { suspend_count = %i, virtual_size = 0x%8.8llx, resident_size = 0x%8.8llx, user_time = %f, system_time = %f }",
447                        info->suspend_count,
448                        (uint64_t)info->virtual_size,
449                        (uint64_t)info->resident_size,
450                        user,
451                        system);
452    }
453    return err.Error();
454}
455
456
457//----------------------------------------------------------------------
458// MachTask::IsValid
459//
460// Returns true if a task is a valid task port for a current process.
461//----------------------------------------------------------------------
462bool
463MachTask::IsValid () const
464{
465    return MachTask::IsValid(TaskPort());
466}
467
468//----------------------------------------------------------------------
469// MachTask::IsValid
470//
471// Returns true if a task is a valid task port for a current process.
472//----------------------------------------------------------------------
473bool
474MachTask::IsValid (task_t task)
475{
476    if (task != TASK_NULL)
477    {
478        struct task_basic_info task_info;
479        return BasicInfo(task, &task_info) == KERN_SUCCESS;
480    }
481    return false;
482}
483
484
485bool
486MachTask::StartExceptionThread(DNBError &err)
487{
488    DNBLogThreadedIf(LOG_EXCEPTIONS, "MachTask::%s ( )", __FUNCTION__);
489    task_t task = TaskPortForProcessID(err);
490    if (MachTask::IsValid(task))
491    {
492        // Got the mach port for the current process
493        mach_port_t task_self = mach_task_self ();
494
495        // Allocate an exception port that we will use to track our child process
496        err = ::mach_port_allocate (task_self, MACH_PORT_RIGHT_RECEIVE, &m_exception_port);
497        if (err.Fail())
498            return false;
499
500        // Add the ability to send messages on the new exception port
501        err = ::mach_port_insert_right (task_self, m_exception_port, m_exception_port, MACH_MSG_TYPE_MAKE_SEND);
502        if (err.Fail())
503            return false;
504
505        // Save the original state of the exception ports for our child process
506        SaveExceptionPortInfo();
507
508        // We weren't able to save the info for our exception ports, we must stop...
509        if (m_exc_port_info.mask == 0)
510        {
511            err.SetErrorString("failed to get exception port info");
512            return false;
513        }
514
515        // Set the ability to get all exceptions on this port
516        err = ::task_set_exception_ports (task, m_exc_port_info.mask, m_exception_port, EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES, THREAD_STATE_NONE);
517        if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail())
518        {
519            err.LogThreaded("::task_set_exception_ports ( task = 0x%4.4x, exception_mask = 0x%8.8x, new_port = 0x%4.4x, behavior = 0x%8.8x, new_flavor = 0x%8.8x )",
520                            task,
521                            m_exc_port_info.mask,
522                            m_exception_port,
523                            (EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES),
524                            THREAD_STATE_NONE);
525        }
526
527        if (err.Fail())
528            return false;
529
530        // Create the exception thread
531        err = ::pthread_create (&m_exception_thread, NULL, MachTask::ExceptionThread, this);
532        return err.Success();
533    }
534    else
535    {
536        DNBLogError("MachTask::%s (): task invalid, exception thread start failed.", __FUNCTION__);
537    }
538    return false;
539}
540
541kern_return_t
542MachTask::ShutDownExcecptionThread()
543{
544    DNBError err;
545
546    err = RestoreExceptionPortInfo();
547
548    // NULL our our exception port and let our exception thread exit
549    mach_port_t exception_port = m_exception_port;
550    m_exception_port = NULL;
551
552    err.SetError(::pthread_cancel(m_exception_thread), DNBError::POSIX);
553    if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
554        err.LogThreaded("::pthread_cancel ( thread = %p )", m_exception_thread);
555
556    err.SetError(::pthread_join(m_exception_thread, NULL), DNBError::POSIX);
557    if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
558        err.LogThreaded("::pthread_join ( thread = %p, value_ptr = NULL)", m_exception_thread);
559
560    // Deallocate our exception port that we used to track our child process
561    mach_port_t task_self = mach_task_self ();
562    err = ::mach_port_deallocate (task_self, exception_port);
563    if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
564        err.LogThreaded("::mach_port_deallocate ( task = 0x%4.4x, name = 0x%4.4x )", task_self, exception_port);
565
566    return err.Error();
567}
568
569
570void *
571MachTask::ExceptionThread (void *arg)
572{
573    if (arg == NULL)
574        return NULL;
575
576    MachTask *mach_task = (MachTask*) arg;
577    MachProcess *mach_proc = mach_task->Process();
578    DNBLogThreadedIf(LOG_EXCEPTIONS, "MachTask::%s ( arg = %p ) starting thread...", __FUNCTION__, arg);
579
580    // We keep a count of the number of consecutive exceptions received so
581    // we know to grab all exceptions without a timeout. We do this to get a
582    // bunch of related exceptions on our exception port so we can process
583    // then together. When we have multiple threads, we can get an exception
584    // per thread and they will come in consecutively. The main loop in this
585    // thread can stop periodically if needed to service things related to this
586    // process.
587    // flag set in the options, so we will wait forever for an exception on
588    // our exception port. After we get one exception, we then will use the
589    // MACH_RCV_TIMEOUT option with a zero timeout to grab all other current
590    // exceptions for our process. After we have received the last pending
591    // exception, we will get a timeout which enables us to then notify
592    // our main thread that we have an exception bundle avaiable. We then wait
593    // for the main thread to tell this exception thread to start trying to get
594    // exceptions messages again and we start again with a mach_msg read with
595    // infinite timeout.
596    uint32_t num_exceptions_received = 0;
597    DNBError err;
598    task_t task = mach_task->TaskPort();
599    mach_msg_timeout_t periodic_timeout = 0;
600
601#ifdef WITH_SPRINGBOARD
602    mach_msg_timeout_t watchdog_elapsed = 0;
603    mach_msg_timeout_t watchdog_timeout = 60 * 1000;
604    pid_t pid = mach_proc->ProcessID();
605    CFReleaser<SBSWatchdogAssertionRef> watchdog;
606
607    if (mach_proc->ProcessUsingSpringBoard())
608    {
609        // Request a renewal for every 60 seconds if we attached using SpringBoard
610        watchdog.reset(::SBSWatchdogAssertionCreateForPID(NULL, pid, 60));
611        DNBLogThreadedIf(LOG_TASK, "::SBSWatchdogAssertionCreateForPID (NULL, %4.4x, 60 ) => %p", pid, watchdog.get());
612
613        if (watchdog.get())
614        {
615            ::SBSWatchdogAssertionRenew (watchdog.get());
616
617            CFTimeInterval watchdogRenewalInterval = ::SBSWatchdogAssertionGetRenewalInterval (watchdog.get());
618            DNBLogThreadedIf(LOG_TASK, "::SBSWatchdogAssertionGetRenewalInterval ( %p ) => %g seconds", watchdog.get(), watchdogRenewalInterval);
619            if (watchdogRenewalInterval > 0.0)
620            {
621                watchdog_timeout = (mach_msg_timeout_t)watchdogRenewalInterval * 1000;
622                if (watchdog_timeout > 3000)
623                    watchdog_timeout -= 1000;   // Give us a second to renew our timeout
624                else if (watchdog_timeout > 1000)
625                    watchdog_timeout -= 250;    // Give us a quarter of a second to renew our timeout
626            }
627        }
628        if (periodic_timeout == 0 || periodic_timeout > watchdog_timeout)
629            periodic_timeout = watchdog_timeout;
630    }
631#endif  // #ifdef WITH_SPRINGBOARD
632
633    while (mach_task->ExceptionPortIsValid())
634    {
635        ::pthread_testcancel ();
636
637        MachException::Message exception_message;
638
639
640        if (num_exceptions_received > 0)
641        {
642            // No timeout, just receive as many exceptions as we can since we already have one and we want
643            // to get all currently available exceptions for this task
644            err = exception_message.Receive(mach_task->ExceptionPort(), MACH_RCV_MSG | MACH_RCV_INTERRUPT | MACH_RCV_TIMEOUT, 0);
645        }
646        else if (periodic_timeout > 0)
647        {
648            // We need to stop periodically in this loop, so try and get a mach message with a valid timeout (ms)
649            err = exception_message.Receive(mach_task->ExceptionPort(), MACH_RCV_MSG | MACH_RCV_INTERRUPT | MACH_RCV_TIMEOUT, periodic_timeout);
650        }
651        else
652        {
653            // We don't need to parse all current exceptions or stop periodically,
654            // just wait for an exception forever.
655            err = exception_message.Receive(mach_task->ExceptionPort(), MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0);
656        }
657
658        if (err.Error() == MACH_RCV_INTERRUPTED)
659        {
660            // If we have no task port we should exit this thread
661            if (!mach_task->ExceptionPortIsValid())
662            {
663                DNBLogThreadedIf(LOG_EXCEPTIONS, "thread cancelled...");
664                break;
665            }
666
667            // Make sure our task is still valid
668            if (MachTask::IsValid(task))
669            {
670                // Task is still ok
671                DNBLogThreadedIf(LOG_EXCEPTIONS, "interrupted, but task still valid, continuing...");
672                continue;
673            }
674            else
675            {
676                DNBLogThreadedIf(LOG_EXCEPTIONS, "task has exited...");
677                mach_proc->SetState(eStateExited);
678                // Our task has died, exit the thread.
679                break;
680            }
681        }
682        else if (err.Error() == MACH_RCV_TIMED_OUT)
683        {
684            if (num_exceptions_received > 0)
685            {
686                // We were receiving all current exceptions with a timeout of zero
687                // it is time to go back to our normal looping mode
688                num_exceptions_received = 0;
689
690                // Notify our main thread we have a complete exception message
691                // bundle available.
692                mach_proc->ExceptionMessageBundleComplete();
693
694                // in case we use a timeout value when getting exceptions...
695                // Make sure our task is still valid
696                if (MachTask::IsValid(task))
697                {
698                    // Task is still ok
699                    DNBLogThreadedIf(LOG_EXCEPTIONS, "got a timeout, continuing...");
700                    continue;
701                }
702                else
703                {
704                    DNBLogThreadedIf(LOG_EXCEPTIONS, "task has exited...");
705                    mach_proc->SetState(eStateExited);
706                    // Our task has died, exit the thread.
707                    break;
708                }
709                continue;
710            }
711
712#ifdef WITH_SPRINGBOARD
713            if (watchdog.get())
714            {
715                watchdog_elapsed += periodic_timeout;
716                if (watchdog_elapsed >= watchdog_timeout)
717                {
718                    DNBLogThreadedIf(LOG_TASK, "SBSWatchdogAssertionRenew ( %p )", watchdog.get());
719                    ::SBSWatchdogAssertionRenew (watchdog.get());
720                    watchdog_elapsed = 0;
721                }
722            }
723#endif
724        }
725        else if (err.Error() != KERN_SUCCESS)
726        {
727            DNBLogThreadedIf(LOG_EXCEPTIONS, "got some other error, do something about it??? nah, continuing for now...");
728            // TODO: notify of error?
729        }
730        else
731        {
732            if (exception_message.CatchExceptionRaise(task))
733            {
734                ++num_exceptions_received;
735                mach_proc->ExceptionMessageReceived(exception_message);
736            }
737        }
738    }
739
740#ifdef WITH_SPRINGBOARD
741    if (watchdog.get())
742    {
743        // TODO: change SBSWatchdogAssertionRelease to SBSWatchdogAssertionCancel when we
744        // all are up and running on systems that support it. The SBS framework has a #define
745        // that will forward SBSWatchdogAssertionRelease to SBSWatchdogAssertionCancel for now
746        // so it should still build either way.
747        DNBLogThreadedIf(LOG_TASK, "::SBSWatchdogAssertionRelease(%p)", watchdog.get());
748        ::SBSWatchdogAssertionRelease (watchdog.get());
749    }
750#endif  // #ifdef WITH_SPRINGBOARD
751
752    DNBLogThreadedIf(LOG_EXCEPTIONS, "MachTask::%s (%p): thread exiting...", __FUNCTION__, arg);
753    return NULL;
754}
755
756
757// So the TASK_DYLD_INFO used to just return the address of the all image infos
758// as a single member called "all_image_info". Then someone decided it would be
759// a good idea to rename this first member to "all_image_info_addr" and add a
760// size member called "all_image_info_size". This of course can not be detected
761// using code or #defines. So to hack around this problem, we define our own
762// version of the TASK_DYLD_INFO structure so we can guarantee what is inside it.
763
764struct hack_task_dyld_info {
765    mach_vm_address_t   all_image_info_addr;
766    mach_vm_size_t      all_image_info_size;
767};
768
769nub_addr_t
770MachTask::GetDYLDAllImageInfosAddress (DNBError& err)
771{
772    struct hack_task_dyld_info dyld_info;
773    mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
774    // Make sure that COUNT isn't bigger than our hacked up struct hack_task_dyld_info.
775    // If it is, then make COUNT smaller to match.
776    if (count > (sizeof(struct hack_task_dyld_info) / sizeof(natural_t)))
777        count = (sizeof(struct hack_task_dyld_info) / sizeof(natural_t));
778
779    task_t task = TaskPortForProcessID (err);
780    if (err.Success())
781    {
782        err = ::task_info (task, TASK_DYLD_INFO, (task_info_t)&dyld_info, &count);
783        if (err.Success())
784        {
785            // We now have the address of the all image infos structure
786            return dyld_info.all_image_info_addr;
787        }
788    }
789    return INVALID_NUB_ADDRESS;
790}
791
792
793//----------------------------------------------------------------------
794// MachTask::AllocateMemory
795//----------------------------------------------------------------------
796nub_addr_t
797MachTask::AllocateMemory (size_t size, uint32_t permissions)
798{
799    mach_vm_address_t addr;
800    task_t task = TaskPort();
801    if (task == TASK_NULL)
802        return INVALID_NUB_ADDRESS;
803
804    DNBError err;
805    err = ::mach_vm_allocate (task, &addr, size, TRUE);
806    if (err.Error() == KERN_SUCCESS)
807    {
808        // Set the protections:
809        vm_prot_t mach_prot = VM_PROT_NONE;
810        if (permissions & eMemoryPermissionsReadable)
811            mach_prot |= VM_PROT_READ;
812        if (permissions & eMemoryPermissionsWritable)
813            mach_prot |= VM_PROT_WRITE;
814        if (permissions & eMemoryPermissionsExecutable)
815            mach_prot |= VM_PROT_EXECUTE;
816
817
818        err = ::mach_vm_protect (task, addr, size, 0, mach_prot);
819        if (err.Error() == KERN_SUCCESS)
820        {
821            m_allocations.insert (std::make_pair(addr, size));
822            return addr;
823        }
824        ::mach_vm_deallocate (task, addr, size);
825    }
826    return INVALID_NUB_ADDRESS;
827}
828
829//----------------------------------------------------------------------
830// MachTask::DeallocateMemory
831//----------------------------------------------------------------------
832nub_bool_t
833MachTask::DeallocateMemory (nub_addr_t addr)
834{
835    task_t task = TaskPort();
836    if (task == TASK_NULL)
837        return false;
838
839    // We have to stash away sizes for the allocations...
840    allocation_collection::iterator pos, end = m_allocations.end();
841    for (pos = m_allocations.begin(); pos != end; pos++)
842    {
843        if ((*pos).first == addr)
844        {
845            m_allocations.erase(pos);
846#define ALWAYS_ZOMBIE_ALLOCATIONS 0
847            if (ALWAYS_ZOMBIE_ALLOCATIONS || getenv ("DEBUGSERVER_ZOMBIE_ALLOCATIONS"))
848            {
849                ::mach_vm_protect (task, (*pos).first, (*pos).second, 0, VM_PROT_NONE);
850                return true;
851            }
852            else
853                return ::mach_vm_deallocate (task, (*pos).first, (*pos).second) == KERN_SUCCESS;
854        }
855
856    }
857    return false;
858}
859
860static void foundStackLog(mach_stack_logging_record_t record, void *context) {
861    *((bool*)context) = true;
862}
863
864bool
865MachTask::HasMallocLoggingEnabled ()
866{
867    bool found = false;
868
869    __mach_stack_logging_enumerate_records(m_task, 0x0, foundStackLog, &found);
870    return found;
871}
872
873struct history_enumerator_impl_data
874{
875    MachMallocEvent *buffer;
876    uint32_t        *position;
877    uint32_t         count;
878};
879
880static void history_enumerator_impl(mach_stack_logging_record_t record, void* enum_obj)
881{
882    history_enumerator_impl_data *data = (history_enumerator_impl_data*)enum_obj;
883
884    if (*data->position >= data->count)
885        return;
886
887    data->buffer[*data->position].m_base_address = record.address;
888    data->buffer[*data->position].m_size = record.argument;
889    data->buffer[*data->position].m_event_id = record.stack_identifier;
890    data->buffer[*data->position].m_event_type = record.type_flags == stack_logging_type_alloc ?   eMachMallocEventTypeAlloc :
891                                                 record.type_flags == stack_logging_type_dealloc ? eMachMallocEventTypeDealloc :
892                                                                                                   eMachMallocEventTypeOther;
893    *data->position+=1;
894}
895
896bool
897MachTask::EnumerateMallocRecords (MachMallocEvent *event_buffer,
898                                  uint32_t buffer_size,
899                                  uint32_t *count)
900{
901    return EnumerateMallocRecords(0,
902                                  event_buffer,
903                                  buffer_size,
904                                  count);
905}
906
907bool
908MachTask::EnumerateMallocRecords (mach_vm_address_t address,
909                                  MachMallocEvent *event_buffer,
910                                  uint32_t buffer_size,
911                                  uint32_t *count)
912{
913    if (!event_buffer || !count)
914        return false;
915
916    if (buffer_size == 0)
917        return false;
918
919    *count = 0;
920    history_enumerator_impl_data data = { event_buffer, count, buffer_size };
921    __mach_stack_logging_enumerate_records(m_task, address, history_enumerator_impl, &data);
922    return (*count > 0);
923}
924
925bool
926MachTask::EnumerateMallocFrames (MachMallocEventId event_id,
927                                 mach_vm_address_t *function_addresses_buffer,
928                                 uint32_t buffer_size,
929                                 uint32_t *count)
930{
931    if (!function_addresses_buffer || !count)
932        return false;
933
934    if (buffer_size == 0)
935        return false;
936
937    __mach_stack_logging_frames_for_uniqued_stack(m_task, event_id, &function_addresses_buffer[0], buffer_size, count);
938    *count -= 1;
939    if (function_addresses_buffer[*count-1] < vm_page_size)
940        *count -= 1;
941    return (*count > 0);
942}
943