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