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