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