MachTask.cpp revision 851e30ec6a1b1d2c154bb7d69ed0d05b5fd14705
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 = %llu, buf = %p) => %llu bytes read", (uint64_t)addr, (uint64_t)size, buf, (uint64_t)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 = %llu, buf = %p) => %llu bytes written", (uint64_t)addr, (uint64_t)size, buf, (uint64_t)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
428    return err.Error();
429}
430
431
432void *
433MachTask::ExceptionThread (void *arg)
434{
435    if (arg == NULL)
436        return NULL;
437
438    MachTask *mach_task = (MachTask*) arg;
439    MachProcess *mach_proc = mach_task->Process();
440    DNBLogThreadedIf(LOG_EXCEPTIONS, "MachTask::%s ( arg = %p ) starting thread...", __FUNCTION__, arg);
441
442    // We keep a count of the number of consecutive exceptions received so
443    // we know to grab all exceptions without a timeout. We do this to get a
444    // bunch of related exceptions on our exception port so we can process
445    // then together. When we have multiple threads, we can get an exception
446    // per thread and they will come in consecutively. The main loop in this
447    // thread can stop periodically if needed to service things related to this
448    // process.
449    // flag set in the options, so we will wait forever for an exception on
450    // our exception port. After we get one exception, we then will use the
451    // MACH_RCV_TIMEOUT option with a zero timeout to grab all other current
452    // exceptions for our process. After we have received the last pending
453    // exception, we will get a timeout which enables us to then notify
454    // our main thread that we have an exception bundle avaiable. We then wait
455    // for the main thread to tell this exception thread to start trying to get
456    // exceptions messages again and we start again with a mach_msg read with
457    // infinite timeout.
458    uint32_t num_exceptions_received = 0;
459    DNBError err;
460    task_t task = mach_task->TaskPort();
461    mach_msg_timeout_t periodic_timeout = 0;
462
463#ifdef WITH_SPRINGBOARD
464    mach_msg_timeout_t watchdog_elapsed = 0;
465    mach_msg_timeout_t watchdog_timeout = 60 * 1000;
466    pid_t pid = mach_proc->ProcessID();
467    CFReleaser<SBSWatchdogAssertionRef> watchdog;
468
469    if (mach_proc->ProcessUsingSpringBoard())
470    {
471        // Request a renewal for every 60 seconds if we attached using SpringBoard
472        watchdog.reset(::SBSWatchdogAssertionCreateForPID(NULL, pid, 60));
473        DNBLogThreadedIf(LOG_TASK, "::SBSWatchdogAssertionCreateForPID (NULL, %4.4x, 60 ) => %p", pid, watchdog.get());
474
475        if (watchdog.get())
476        {
477            ::SBSWatchdogAssertionRenew (watchdog.get());
478
479            CFTimeInterval watchdogRenewalInterval = ::SBSWatchdogAssertionGetRenewalInterval (watchdog.get());
480            DNBLogThreadedIf(LOG_TASK, "::SBSWatchdogAssertionGetRenewalInterval ( %p ) => %g seconds", watchdog.get(), watchdogRenewalInterval);
481            if (watchdogRenewalInterval > 0.0)
482            {
483                watchdog_timeout = (mach_msg_timeout_t)watchdogRenewalInterval * 1000;
484                if (watchdog_timeout > 3000)
485                    watchdog_timeout -= 1000;   // Give us a second to renew our timeout
486                else if (watchdog_timeout > 1000)
487                    watchdog_timeout -= 250;    // Give us a quarter of a second to renew our timeout
488            }
489        }
490        if (periodic_timeout == 0 || periodic_timeout > watchdog_timeout)
491            periodic_timeout = watchdog_timeout;
492    }
493#endif  // #ifdef WITH_SPRINGBOARD
494
495    while (mach_task->ExceptionPortIsValid())
496    {
497        ::pthread_testcancel ();
498
499        MachException::Message exception_message;
500
501
502        if (num_exceptions_received > 0)
503        {
504            // No timeout, just receive as many exceptions as we can since we already have one and we want
505            // to get all currently available exceptions for this task
506            err = exception_message.Receive(mach_task->ExceptionPort(), MACH_RCV_MSG | MACH_RCV_INTERRUPT | MACH_RCV_TIMEOUT, 0);
507        }
508        else if (periodic_timeout > 0)
509        {
510            // We need to stop periodically in this loop, so try and get a mach message with a valid timeout (ms)
511            err = exception_message.Receive(mach_task->ExceptionPort(), MACH_RCV_MSG | MACH_RCV_INTERRUPT | MACH_RCV_TIMEOUT, periodic_timeout);
512        }
513        else
514        {
515            // We don't need to parse all current exceptions or stop periodically,
516            // just wait for an exception forever.
517            err = exception_message.Receive(mach_task->ExceptionPort(), MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0);
518        }
519
520        if (err.Error() == MACH_RCV_INTERRUPTED)
521        {
522            // If we have no task port we should exit this thread
523            if (!mach_task->ExceptionPortIsValid())
524            {
525                DNBLogThreadedIf(LOG_EXCEPTIONS, "thread cancelled...");
526                break;
527            }
528
529            // Make sure our task is still valid
530            if (MachTask::IsValid(task))
531            {
532                // Task is still ok
533                DNBLogThreadedIf(LOG_EXCEPTIONS, "interrupted, but task still valid, continuing...");
534                continue;
535            }
536            else
537            {
538                DNBLogThreadedIf(LOG_EXCEPTIONS, "task has exited...");
539                mach_proc->SetState(eStateExited);
540                // Our task has died, exit the thread.
541                break;
542            }
543        }
544        else if (err.Error() == MACH_RCV_TIMED_OUT)
545        {
546            if (num_exceptions_received > 0)
547            {
548                // We were receiving all current exceptions with a timeout of zero
549                // it is time to go back to our normal looping mode
550                num_exceptions_received = 0;
551
552                // Notify our main thread we have a complete exception message
553                // bundle available.
554                mach_proc->ExceptionMessageBundleComplete();
555
556                // in case we use a timeout value when getting exceptions...
557                // Make sure our task is still valid
558                if (MachTask::IsValid(task))
559                {
560                    // Task is still ok
561                    DNBLogThreadedIf(LOG_EXCEPTIONS, "got a timeout, continuing...");
562                    continue;
563                }
564                else
565                {
566                    DNBLogThreadedIf(LOG_EXCEPTIONS, "task has exited...");
567                    mach_proc->SetState(eStateExited);
568                    // Our task has died, exit the thread.
569                    break;
570                }
571                continue;
572            }
573
574#ifdef WITH_SPRINGBOARD
575            if (watchdog.get())
576            {
577                watchdog_elapsed += periodic_timeout;
578                if (watchdog_elapsed >= watchdog_timeout)
579                {
580                    DNBLogThreadedIf(LOG_TASK, "SBSWatchdogAssertionRenew ( %p )", watchdog.get());
581                    ::SBSWatchdogAssertionRenew (watchdog.get());
582                    watchdog_elapsed = 0;
583                }
584            }
585#endif
586        }
587        else if (err.Error() != KERN_SUCCESS)
588        {
589            DNBLogThreadedIf(LOG_EXCEPTIONS, "got some other error, do something about it??? nah, continuing for now...");
590            // TODO: notify of error?
591        }
592        else
593        {
594            if (exception_message.CatchExceptionRaise(task))
595            {
596                ++num_exceptions_received;
597                mach_proc->ExceptionMessageReceived(exception_message);
598            }
599        }
600    }
601
602#ifdef WITH_SPRINGBOARD
603    if (watchdog.get())
604    {
605        // TODO: change SBSWatchdogAssertionRelease to SBSWatchdogAssertionCancel when we
606        // all are up and running on systems that support it. The SBS framework has a #define
607        // that will forward SBSWatchdogAssertionRelease to SBSWatchdogAssertionCancel for now
608        // so it should still build either way.
609        DNBLogThreadedIf(LOG_TASK, "::SBSWatchdogAssertionRelease(%p)", watchdog.get());
610        ::SBSWatchdogAssertionRelease (watchdog.get());
611    }
612#endif  // #ifdef WITH_SPRINGBOARD
613
614    DNBLogThreadedIf(LOG_EXCEPTIONS, "MachTask::%s (%p): thread exiting...", __FUNCTION__, arg);
615    return NULL;
616}
617
618
619// So the TASK_DYLD_INFO used to just return the address of the all image infos
620// as a single member called "all_image_info". Then someone decided it would be
621// a good idea to rename this first member to "all_image_info_addr" and add a
622// size member called "all_image_info_size". This of course can not be detected
623// using code or #defines. So to hack around this problem, we define our own
624// version of the TASK_DYLD_INFO structure so we can guarantee what is inside it.
625
626struct hack_task_dyld_info {
627    mach_vm_address_t   all_image_info_addr;
628    mach_vm_size_t      all_image_info_size;
629};
630
631nub_addr_t
632MachTask::GetDYLDAllImageInfosAddress (DNBError& err)
633{
634    struct hack_task_dyld_info dyld_info;
635    mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
636    // Make sure that COUNT isn't bigger than our hacked up struct hack_task_dyld_info.
637    // If it is, then make COUNT smaller to match.
638    if (count > (sizeof(struct hack_task_dyld_info) / sizeof(natural_t)))
639        count = (sizeof(struct hack_task_dyld_info) / sizeof(natural_t));
640
641    task_t task = TaskPortForProcessID (err);
642    if (err.Success())
643    {
644        err = ::task_info (task, TASK_DYLD_INFO, (task_info_t)&dyld_info, &count);
645        if (err.Success())
646        {
647            // We now have the address of the all image infos structure
648            return dyld_info.all_image_info_addr;
649        }
650    }
651    return INVALID_NUB_ADDRESS;
652}
653
654
655//----------------------------------------------------------------------
656// MachTask::AllocateMemory
657//----------------------------------------------------------------------
658nub_addr_t
659MachTask::AllocateMemory (size_t size, uint32_t permissions)
660{
661    mach_vm_address_t addr;
662    task_t task = TaskPort();
663    if (task == TASK_NULL)
664        return INVALID_NUB_ADDRESS;
665
666    DNBError err;
667    err = ::mach_vm_allocate (task, &addr, size, TRUE);
668    if (err.Error() == KERN_SUCCESS)
669    {
670        // Set the protections:
671        vm_prot_t mach_prot = VM_PROT_NONE;
672        if (permissions & eMemoryPermissionsReadable)
673            mach_prot |= VM_PROT_READ;
674        if (permissions & eMemoryPermissionsWritable)
675            mach_prot |= VM_PROT_WRITE;
676        if (permissions & eMemoryPermissionsExecutable)
677            mach_prot |= VM_PROT_EXECUTE;
678
679
680        err = ::mach_vm_protect (task, addr, size, 0, mach_prot);
681        if (err.Error() == KERN_SUCCESS)
682        {
683            m_allocations.insert (std::make_pair(addr, size));
684            return addr;
685        }
686        ::mach_vm_deallocate (task, addr, size);
687    }
688    return INVALID_NUB_ADDRESS;
689}
690
691//----------------------------------------------------------------------
692// MachTask::DeallocateMemory
693//----------------------------------------------------------------------
694nub_bool_t
695MachTask::DeallocateMemory (nub_addr_t addr)
696{
697    task_t task = TaskPort();
698    if (task == TASK_NULL)
699        return false;
700
701    // We have to stash away sizes for the allocations...
702    allocation_collection::iterator pos, end = m_allocations.end();
703    for (pos = m_allocations.begin(); pos != end; pos++)
704    {
705        if ((*pos).first == addr)
706        {
707            m_allocations.erase(pos);
708#define ALWAYS_ZOMBIE_ALLOCATIONS 0
709            if (ALWAYS_ZOMBIE_ALLOCATIONS || getenv ("DEBUGSERVER_ZOMBIE_ALLOCATIONS"))
710            {
711                ::mach_vm_protect (task, (*pos).first, (*pos).second, 0, VM_PROT_NONE);
712                return true;
713            }
714            else
715                return ::mach_vm_deallocate (task, (*pos).first, (*pos).second) == KERN_SUCCESS;
716        }
717
718    }
719    return false;
720}
721
722static void foundStackLog(mach_stack_logging_record_t record, void *context) {
723    *((bool*)context) = true;
724}
725
726bool
727MachTask::HasMallocLoggingEnabled ()
728{
729    bool found = false;
730
731    __mach_stack_logging_enumerate_records(m_task, 0x0, foundStackLog, &found);
732    return found;
733}
734
735struct history_enumerator_impl_data
736{
737    MachMallocEvent *buffer;
738    uint32_t        *position;
739    uint32_t         count;
740};
741
742static void history_enumerator_impl(mach_stack_logging_record_t record, void* enum_obj)
743{
744    history_enumerator_impl_data *data = (history_enumerator_impl_data*)enum_obj;
745
746    if (*data->position >= data->count)
747        return;
748
749    data->buffer[*data->position].m_base_address = record.address;
750    data->buffer[*data->position].m_size = record.argument;
751    data->buffer[*data->position].m_event_id = record.stack_identifier;
752    data->buffer[*data->position].m_event_type = record.type_flags == stack_logging_type_alloc ?   eMachMallocEventTypeAlloc :
753                                                 record.type_flags == stack_logging_type_dealloc ? eMachMallocEventTypeDealloc :
754                                                                                                   eMachMallocEventTypeOther;
755    *data->position+=1;
756}
757
758bool
759MachTask::EnumerateMallocRecords (MachMallocEvent *event_buffer,
760                                  uint32_t buffer_size,
761                                  uint32_t *count)
762{
763    return EnumerateMallocRecords(0,
764                                  event_buffer,
765                                  buffer_size,
766                                  count);
767}
768
769bool
770MachTask::EnumerateMallocRecords (mach_vm_address_t address,
771                                  MachMallocEvent *event_buffer,
772                                  uint32_t buffer_size,
773                                  uint32_t *count)
774{
775    if (!event_buffer || !count)
776        return false;
777
778    if (buffer_size == 0)
779        return false;
780
781    *count = 0;
782    history_enumerator_impl_data data = { event_buffer, count, buffer_size };
783    __mach_stack_logging_enumerate_records(m_task, address, history_enumerator_impl, &data);
784    return (*count > 0);
785}
786
787bool
788MachTask::EnumerateMallocFrames (MachMallocEventId event_id,
789                                 mach_vm_address_t *function_addresses_buffer,
790                                 uint32_t buffer_size,
791                                 uint32_t *count)
792{
793    if (!function_addresses_buffer || !count)
794        return false;
795
796    if (buffer_size == 0)
797        return false;
798
799    __mach_stack_logging_frames_for_uniqued_stack(m_task, event_id, &function_addresses_buffer[0], buffer_size, count);
800    *count -= 1;
801    if (function_addresses_buffer[*count-1] < vm_page_size)
802        *count -= 1;
803    return (*count > 0);
804}
805