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