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