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