MachProcess.cpp revision 559cf6e8b52b940f5f4362b32d628838d6301e2e
1//===-- MachProcess.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//  Created by Greg Clayton on 6/15/07.
11//
12//===----------------------------------------------------------------------===//
13
14#include "DNB.h"
15#include <mach/mach.h>
16#include <signal.h>
17#include <spawn.h>
18#include <sys/fcntl.h>
19#include <sys/types.h>
20#include <sys/ptrace.h>
21#include <sys/stat.h>
22#include <sys/sysctl.h>
23#include <unistd.h>
24#include "MacOSX/CFUtils.h"
25#include "SysSignal.h"
26
27#include <algorithm>
28#include <map>
29
30#include "DNBDataRef.h"
31#include "DNBLog.h"
32#include "DNBThreadResumeActions.h"
33#include "DNBTimer.h"
34#include "MachProcess.h"
35#include "PseudoTerminal.h"
36
37#include "CFBundle.h"
38#include "CFData.h"
39#include "CFString.h"
40
41static CFStringRef CopyBundleIDForPath (const char *app_buncle_path, DNBError &err_str);
42
43#ifdef WITH_SPRINGBOARD
44
45#include <CoreFoundation/CoreFoundation.h>
46#include <SpringBoardServices/SpringBoardServer.h>
47#include <SpringBoardServices/SBSWatchdogAssertion.h>
48
49static bool
50IsSBProcess (nub_process_t pid)
51{
52    CFReleaser<CFArrayRef> appIdsForPID (::SBSCopyDisplayIdentifiersForProcessID(pid));
53    return appIdsForPID.get() != NULL;
54}
55
56#endif
57
58#if 0
59#define DEBUG_LOG(fmt, ...) printf(fmt, ## __VA_ARGS__)
60#else
61#define DEBUG_LOG(fmt, ...)
62#endif
63
64#ifndef MACH_PROCESS_USE_POSIX_SPAWN
65#define MACH_PROCESS_USE_POSIX_SPAWN 1
66#endif
67
68#ifndef _POSIX_SPAWN_DISABLE_ASLR
69#define _POSIX_SPAWN_DISABLE_ASLR       0x0100
70#endif
71
72MachProcess::MachProcess() :
73    m_pid               (0),
74    m_cpu_type          (0),
75    m_child_stdin       (-1),
76    m_child_stdout      (-1),
77    m_child_stderr      (-1),
78    m_path              (),
79    m_args              (),
80    m_task              (this),
81    m_flags             (eMachProcessFlagsNone),
82    m_stdio_thread      (0),
83    m_stdio_mutex       (PTHREAD_MUTEX_RECURSIVE),
84    m_stdout_data       (),
85    m_thread_actions    (),
86    m_profile_enabled   (false),
87    m_profile_interval_usec (0),
88    m_profile_thread    (0),
89    m_profile_data_mutex(PTHREAD_MUTEX_RECURSIVE),
90    m_profile_data      (),
91    m_thread_list        (),
92    m_exception_messages (),
93    m_exception_messages_mutex (PTHREAD_MUTEX_RECURSIVE),
94    m_state             (eStateUnloaded),
95    m_state_mutex       (PTHREAD_MUTEX_RECURSIVE),
96    m_events            (0, kAllEventsMask),
97    m_breakpoints       (),
98    m_watchpoints       (),
99    m_name_to_addr_callback(NULL),
100    m_name_to_addr_baton(NULL),
101    m_image_infos_callback(NULL),
102    m_image_infos_baton(NULL)
103{
104    DNBLogThreadedIf(LOG_PROCESS | LOG_VERBOSE, "%s", __PRETTY_FUNCTION__);
105}
106
107MachProcess::~MachProcess()
108{
109    DNBLogThreadedIf(LOG_PROCESS | LOG_VERBOSE, "%s", __PRETTY_FUNCTION__);
110    Clear();
111}
112
113pid_t
114MachProcess::SetProcessID(pid_t pid)
115{
116    // Free any previous process specific data or resources
117    Clear();
118    // Set the current PID appropriately
119    if (pid == 0)
120        m_pid = ::getpid ();
121    else
122        m_pid = pid;
123    return m_pid;    // Return actualy PID in case a zero pid was passed in
124}
125
126nub_state_t
127MachProcess::GetState()
128{
129    // If any other threads access this we will need a mutex for it
130    PTHREAD_MUTEX_LOCKER(locker, m_state_mutex);
131    return m_state;
132}
133
134const char *
135MachProcess::ThreadGetName(nub_thread_t tid)
136{
137    return m_thread_list.GetName(tid);
138}
139
140nub_state_t
141MachProcess::ThreadGetState(nub_thread_t tid)
142{
143    return m_thread_list.GetState(tid);
144}
145
146
147nub_size_t
148MachProcess::GetNumThreads () const
149{
150    return m_thread_list.NumThreads();
151}
152
153nub_thread_t
154MachProcess::GetThreadAtIndex (nub_size_t thread_idx) const
155{
156    return m_thread_list.ThreadIDAtIndex(thread_idx);
157}
158
159nub_bool_t
160MachProcess::SyncThreadState (nub_thread_t tid)
161{
162    MachThreadSP thread_sp(m_thread_list.GetThreadByID(tid));
163    if (!thread_sp)
164        return false;
165    kern_return_t kret = ::thread_abort_safely(thread_sp->ThreadID());
166    DNBLogThreadedIf (LOG_THREAD, "thread = 0x%4.4x calling thread_abort_safely (tid) => %u (GetGPRState() for stop_count = %u)", thread_sp->ThreadID(), kret, thread_sp->Process()->StopCount());
167
168    if (kret == KERN_SUCCESS)
169        return true;
170    else
171        return false;
172
173}
174
175nub_thread_t
176MachProcess::GetCurrentThread ()
177{
178    return m_thread_list.CurrentThreadID();
179}
180
181nub_thread_t
182MachProcess::SetCurrentThread(nub_thread_t tid)
183{
184    return m_thread_list.SetCurrentThread(tid);
185}
186
187bool
188MachProcess::GetThreadStoppedReason(nub_thread_t tid, struct DNBThreadStopInfo *stop_info) const
189{
190    return m_thread_list.GetThreadStoppedReason(tid, stop_info);
191}
192
193void
194MachProcess::DumpThreadStoppedReason(nub_thread_t tid) const
195{
196    return m_thread_list.DumpThreadStoppedReason(tid);
197}
198
199const char *
200MachProcess::GetThreadInfo(nub_thread_t tid) const
201{
202    return m_thread_list.GetThreadInfo(tid);
203}
204
205uint32_t
206MachProcess::GetCPUType ()
207{
208    if (m_cpu_type == 0 && m_pid != 0)
209        m_cpu_type = MachProcess::GetCPUTypeForLocalProcess (m_pid);
210    return m_cpu_type;
211}
212
213const DNBRegisterSetInfo *
214MachProcess::GetRegisterSetInfo (nub_thread_t tid, nub_size_t *num_reg_sets) const
215{
216    MachThreadSP thread_sp (m_thread_list.GetThreadByID (tid));
217    if (thread_sp)
218    {
219        DNBArchProtocol *arch = thread_sp->GetArchProtocol();
220        if (arch)
221            return arch->GetRegisterSetInfo (num_reg_sets);
222    }
223    *num_reg_sets = 0;
224    return NULL;
225}
226
227bool
228MachProcess::GetRegisterValue ( nub_thread_t tid, uint32_t set, uint32_t reg, DNBRegisterValue *value ) const
229{
230    return m_thread_list.GetRegisterValue(tid, set, reg, value);
231}
232
233bool
234MachProcess::SetRegisterValue ( nub_thread_t tid, uint32_t set, uint32_t reg, const DNBRegisterValue *value ) const
235{
236    return m_thread_list.SetRegisterValue(tid, set, reg, value);
237}
238
239void
240MachProcess::SetState(nub_state_t new_state)
241{
242    // If any other threads access this we will need a mutex for it
243    uint32_t event_mask = 0;
244
245    // Scope for mutex locker
246    {
247        PTHREAD_MUTEX_LOCKER(locker, m_state_mutex);
248        DNBLogThreadedIf(LOG_PROCESS, "MachProcess::SetState ( %s )", DNBStateAsString(new_state));
249
250        const nub_state_t old_state = m_state;
251
252        if (old_state != new_state)
253        {
254            if (NUB_STATE_IS_STOPPED(new_state))
255                event_mask = eEventProcessStoppedStateChanged;
256            else
257                event_mask = eEventProcessRunningStateChanged;
258
259            m_state = new_state;
260            if (new_state == eStateStopped)
261                m_stop_count++;
262        }
263    }
264
265    if (event_mask != 0)
266    {
267        m_events.SetEvents (event_mask);
268
269        // Wait for the event bit to reset if a reset ACK is requested
270        m_events.WaitForResetAck(event_mask);
271    }
272
273}
274
275void
276MachProcess::Clear()
277{
278    // Clear any cached thread list while the pid and task are still valid
279
280    m_task.Clear();
281    // Now clear out all member variables
282    m_pid = INVALID_NUB_PROCESS;
283    CloseChildFileDescriptors();
284    m_path.clear();
285    m_args.clear();
286    SetState(eStateUnloaded);
287    m_flags = eMachProcessFlagsNone;
288    m_stop_count = 0;
289    m_thread_list.Clear();
290    {
291        PTHREAD_MUTEX_LOCKER(locker, m_exception_messages_mutex);
292        m_exception_messages.clear();
293    }
294    if (m_profile_thread)
295    {
296        pthread_join(m_profile_thread, NULL);
297        m_profile_thread = NULL;
298    }
299}
300
301
302bool
303MachProcess::StartSTDIOThread()
304{
305    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( )", __FUNCTION__);
306    // Create the thread that watches for the child STDIO
307    return ::pthread_create (&m_stdio_thread, NULL, MachProcess::STDIOThread, this) == 0;
308}
309
310void
311MachProcess::SetAsyncEnableProfiling(bool enable, uint64_t interval_usec)
312{
313    m_profile_enabled = enable;
314    m_profile_interval_usec = interval_usec;
315
316    if (m_profile_enabled && (m_profile_thread == 0))
317    {
318        StartProfileThread();
319    }
320}
321
322bool
323MachProcess::StartProfileThread()
324{
325    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( )", __FUNCTION__);
326    // Create the thread that profiles the inferior and reports back if enabled
327    return ::pthread_create (&m_profile_thread, NULL, MachProcess::ProfileThread, this) == 0;
328}
329
330
331nub_addr_t
332MachProcess::LookupSymbol(const char *name, const char *shlib)
333{
334    if (m_name_to_addr_callback != NULL && name && name[0])
335        return m_name_to_addr_callback(ProcessID(), name, shlib, m_name_to_addr_baton);
336    return INVALID_NUB_ADDRESS;
337}
338
339bool
340MachProcess::Resume (const DNBThreadResumeActions& thread_actions)
341{
342    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Resume ()");
343    nub_state_t state = GetState();
344
345    if (CanResume(state))
346    {
347        m_thread_actions = thread_actions;
348        PrivateResume();
349        return true;
350    }
351    else if (state == eStateRunning)
352    {
353        DNBLogThreadedIf(LOG_PROCESS, "Resume() - task 0x%x is running, ignoring...", m_task.TaskPort());
354        return true;
355    }
356    DNBLogThreadedIf(LOG_PROCESS, "Resume() - task 0x%x can't continue, ignoring...", m_task.TaskPort());
357    return false;
358}
359
360bool
361MachProcess::Kill (const struct timespec *timeout_abstime)
362{
363    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Kill ()");
364    nub_state_t state = DoSIGSTOP(true, false, NULL);
365    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Kill() DoSIGSTOP() state = %s", DNBStateAsString(state));
366    errno = 0;
367    ::ptrace (PT_KILL, m_pid, 0, 0);
368    DNBError err;
369    err.SetErrorToErrno();
370    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Kill() DoSIGSTOP() ::ptrace (PT_KILL, pid=%u, 0, 0) => 0x%8.8x (%s)", m_pid, err.Error(), err.AsString());
371    m_thread_actions = DNBThreadResumeActions (eStateRunning, 0);
372    PrivateResume ();
373    return true;
374}
375
376bool
377MachProcess::Signal (int signal, const struct timespec *timeout_abstime)
378{
379    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Signal (signal = %d, timeout = %p)", signal, timeout_abstime);
380    nub_state_t state = GetState();
381    if (::kill (ProcessID(), signal) == 0)
382    {
383        // If we were running and we have a timeout, wait for the signal to stop
384        if (IsRunning(state) && timeout_abstime)
385        {
386            DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Signal (signal = %d, timeout = %p) waiting for signal to stop process...", signal, timeout_abstime);
387            m_events.WaitForSetEvents(eEventProcessStoppedStateChanged, timeout_abstime);
388            state = GetState();
389            DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Signal (signal = %d, timeout = %p) state = %s", signal, timeout_abstime, DNBStateAsString(state));
390            return !IsRunning (state);
391        }
392        DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Signal (signal = %d, timeout = %p) not waiting...", signal, timeout_abstime);
393        return true;
394    }
395    DNBError err(errno, DNBError::POSIX);
396    err.LogThreadedIfError("kill (pid = %d, signo = %i)", ProcessID(), signal);
397    return false;
398
399}
400
401nub_state_t
402MachProcess::DoSIGSTOP (bool clear_bps_and_wps, bool allow_running, uint32_t *thread_idx_ptr)
403{
404    nub_state_t state = GetState();
405    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::DoSIGSTOP() state = %s", DNBStateAsString (state));
406
407    if (!IsRunning(state))
408    {
409        if (clear_bps_and_wps)
410        {
411            DisableAllBreakpoints (true);
412            DisableAllWatchpoints (true);
413            clear_bps_and_wps = false;
414        }
415
416        // If we already have a thread stopped due to a SIGSTOP, we don't have
417        // to do anything...
418        uint32_t thread_idx = m_thread_list.GetThreadIndexForThreadStoppedWithSignal (SIGSTOP);
419        if (thread_idx_ptr)
420            *thread_idx_ptr = thread_idx;
421        if (thread_idx != UINT32_MAX)
422            return GetState();
423
424        // No threads were stopped with a SIGSTOP, we need to run and halt the
425        // process with a signal
426        DNBLogThreadedIf(LOG_PROCESS, "MachProcess::DoSIGSTOP() state = %s -- resuming process", DNBStateAsString (state));
427        if (allow_running)
428            m_thread_actions = DNBThreadResumeActions (eStateRunning, 0);
429        else
430            m_thread_actions = DNBThreadResumeActions (eStateSuspended, 0);
431
432        PrivateResume ();
433
434        // Reset the event that says we were indeed running
435        m_events.ResetEvents(eEventProcessRunningStateChanged);
436        state = GetState();
437    }
438
439    // We need to be stopped in order to be able to detach, so we need
440    // to send ourselves a SIGSTOP
441
442    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::DoSIGSTOP() state = %s -- sending SIGSTOP", DNBStateAsString (state));
443    struct timespec sigstop_timeout;
444    DNBTimer::OffsetTimeOfDay(&sigstop_timeout, 2, 0);
445    Signal (SIGSTOP, &sigstop_timeout);
446    if (clear_bps_and_wps)
447    {
448        DisableAllBreakpoints (true);
449        DisableAllWatchpoints (true);
450        //clear_bps_and_wps = false;
451    }
452    uint32_t thread_idx = m_thread_list.GetThreadIndexForThreadStoppedWithSignal (SIGSTOP);
453    if (thread_idx_ptr)
454        *thread_idx_ptr = thread_idx;
455    return GetState();
456}
457
458bool
459MachProcess::Detach()
460{
461    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Detach()");
462
463    uint32_t thread_idx = UINT32_MAX;
464    nub_state_t state = DoSIGSTOP(true, true, &thread_idx);
465    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Detach() DoSIGSTOP() returned %s", DNBStateAsString(state));
466
467    {
468        m_thread_actions.Clear();
469        DNBThreadResumeAction thread_action;
470        thread_action.tid = m_thread_list.ThreadIDAtIndex (thread_idx);
471        thread_action.state = eStateRunning;
472        thread_action.signal = -1;
473        thread_action.addr = INVALID_NUB_ADDRESS;
474
475        m_thread_actions.Append (thread_action);
476        m_thread_actions.SetDefaultThreadActionIfNeeded (eStateRunning, 0);
477
478        PTHREAD_MUTEX_LOCKER (locker, m_exception_messages_mutex);
479
480        ReplyToAllExceptions ();
481
482    }
483
484    m_task.ShutDownExcecptionThread();
485
486    // Detach from our process
487    errno = 0;
488    nub_process_t pid = m_pid;
489    int ret = ::ptrace (PT_DETACH, pid, (caddr_t)1, 0);
490    DNBError err(errno, DNBError::POSIX);
491    if (DNBLogCheckLogBit(LOG_PROCESS) || err.Fail() || (ret != 0))
492        err.LogThreaded("::ptrace (PT_DETACH, %u, (caddr_t)1, 0)", pid);
493
494    // Resume our task
495    m_task.Resume();
496
497    // NULL our task out as we have already retored all exception ports
498    m_task.Clear();
499
500    // Clear out any notion of the process we once were
501    Clear();
502
503    SetState(eStateDetached);
504
505    return true;
506}
507
508nub_size_t
509MachProcess::RemoveTrapsFromBuffer (nub_addr_t addr, nub_size_t size, uint8_t *buf) const
510{
511    nub_size_t bytes_removed = 0;
512    const DNBBreakpoint *bp;
513    nub_addr_t intersect_addr;
514    nub_size_t intersect_size;
515    nub_size_t opcode_offset;
516    nub_size_t idx;
517    for (idx = 0; (bp = m_breakpoints.GetByIndex(idx)) != NULL; ++idx)
518    {
519        if (bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset))
520        {
521            assert(addr <= intersect_addr && intersect_addr < addr + size);
522            assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
523            assert(opcode_offset + intersect_size <= bp->ByteSize());
524            nub_size_t buf_offset = intersect_addr - addr;
525            ::memcpy(buf + buf_offset, bp->SavedOpcodeBytes() + opcode_offset, intersect_size);
526        }
527    }
528    return bytes_removed;
529}
530
531//----------------------------------------------------------------------
532// ReadMemory from the MachProcess level will always remove any software
533// breakpoints from the memory buffer before returning. If you wish to
534// read memory and see those traps, read from the MachTask
535// (m_task.ReadMemory()) as that version will give you what is actually
536// in inferior memory.
537//----------------------------------------------------------------------
538nub_size_t
539MachProcess::ReadMemory (nub_addr_t addr, nub_size_t size, void *buf)
540{
541    // We need to remove any current software traps (enabled software
542    // breakpoints) that we may have placed in our tasks memory.
543
544    // First just read the memory as is
545    nub_size_t bytes_read = m_task.ReadMemory(addr, size, buf);
546
547    // Then place any opcodes that fall into this range back into the buffer
548    // before we return this to callers.
549    if (bytes_read > 0)
550        RemoveTrapsFromBuffer (addr, size, (uint8_t *)buf);
551    return bytes_read;
552}
553
554//----------------------------------------------------------------------
555// WriteMemory from the MachProcess level will always write memory around
556// any software breakpoints. Any software breakpoints will have their
557// opcodes modified if they are enabled. Any memory that doesn't overlap
558// with software breakpoints will be written to. If you wish to write to
559// inferior memory without this interference, then write to the MachTask
560// (m_task.WriteMemory()) as that version will always modify inferior
561// memory.
562//----------------------------------------------------------------------
563nub_size_t
564MachProcess::WriteMemory (nub_addr_t addr, nub_size_t size, const void *buf)
565{
566    // We need to write any data that would go where any current software traps
567    // (enabled software breakpoints) any software traps (breakpoints) that we
568    // may have placed in our tasks memory.
569
570    std::map<nub_addr_t, DNBBreakpoint *> addr_to_bp_map;
571    DNBBreakpoint *bp;
572    nub_size_t idx;
573    for (idx = 0; (bp = m_breakpoints.GetByIndex(idx)) != NULL; ++idx)
574    {
575        if (bp->IntersectsRange(addr, size, NULL, NULL, NULL))
576            addr_to_bp_map[bp->Address()] = bp;
577    }
578
579    // If we don't have any software breakpoints that are in this buffer, then
580    // we can just write memory and be done with it.
581    if (addr_to_bp_map.empty())
582        return m_task.WriteMemory(addr, size, buf);
583
584    // If we make it here, we have some breakpoints that overlap and we need
585    // to work around them.
586
587    nub_size_t bytes_written = 0;
588    nub_addr_t intersect_addr;
589    nub_size_t intersect_size;
590    nub_size_t opcode_offset;
591    const uint8_t *ubuf = (const uint8_t *)buf;
592    std::map<nub_addr_t, DNBBreakpoint *>::iterator pos, end = addr_to_bp_map.end();
593    for (pos = addr_to_bp_map.begin(); pos != end; ++pos)
594    {
595        bp = pos->second;
596
597        assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
598        assert(addr <= intersect_addr && intersect_addr < addr + size);
599        assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
600        assert(opcode_offset + intersect_size <= bp->ByteSize());
601
602        // Check for bytes before this breakpoint
603        const nub_addr_t curr_addr = addr + bytes_written;
604        if (intersect_addr > curr_addr)
605        {
606            // There are some bytes before this breakpoint that we need to
607            // just write to memory
608            nub_size_t curr_size = intersect_addr - curr_addr;
609            nub_size_t curr_bytes_written = m_task.WriteMemory(curr_addr, curr_size, ubuf + bytes_written);
610            bytes_written += curr_bytes_written;
611            if (curr_bytes_written != curr_size)
612            {
613                // We weren't able to write all of the requested bytes, we
614                // are done looping and will return the number of bytes that
615                // we have written so far.
616                break;
617            }
618        }
619
620        // Now write any bytes that would cover up any software breakpoints
621        // directly into the breakpoint opcode buffer
622        ::memcpy(bp->SavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
623        bytes_written += intersect_size;
624    }
625
626    // Write any remaining bytes after the last breakpoint if we have any left
627    if (bytes_written < size)
628        bytes_written += m_task.WriteMemory(addr + bytes_written, size - bytes_written, ubuf + bytes_written);
629
630    return bytes_written;
631}
632
633void
634MachProcess::ReplyToAllExceptions ()
635{
636    PTHREAD_MUTEX_LOCKER(locker, m_exception_messages_mutex);
637    if (m_exception_messages.empty() == false)
638    {
639        MachException::Message::iterator pos;
640        MachException::Message::iterator begin = m_exception_messages.begin();
641        MachException::Message::iterator end = m_exception_messages.end();
642        for (pos = begin; pos != end; ++pos)
643        {
644            DNBLogThreadedIf(LOG_EXCEPTIONS, "Replying to exception %u...", (uint32_t)std::distance(begin, pos));
645            int thread_reply_signal = 0;
646
647            const DNBThreadResumeAction *action = m_thread_actions.GetActionForThread (pos->state.thread_port, false);
648
649            if (action)
650            {
651                thread_reply_signal = action->signal;
652                if (thread_reply_signal)
653                    m_thread_actions.SetSignalHandledForThread (pos->state.thread_port);
654            }
655
656            DNBError err (pos->Reply(this, thread_reply_signal));
657            if (DNBLogCheckLogBit(LOG_EXCEPTIONS))
658                err.LogThreadedIfError("Error replying to exception");
659        }
660
661        // Erase all exception message as we should have used and replied
662        // to them all already.
663        m_exception_messages.clear();
664    }
665}
666void
667MachProcess::PrivateResume ()
668{
669    PTHREAD_MUTEX_LOCKER (locker, m_exception_messages_mutex);
670
671    ReplyToAllExceptions ();
672//    bool stepOverBreakInstruction = step;
673
674    // Let the thread prepare to resume and see if any threads want us to
675    // step over a breakpoint instruction (ProcessWillResume will modify
676    // the value of stepOverBreakInstruction).
677    m_thread_list.ProcessWillResume (this, m_thread_actions);
678
679    // Set our state accordingly
680    if (m_thread_actions.NumActionsWithState(eStateStepping))
681        SetState (eStateStepping);
682    else
683        SetState (eStateRunning);
684
685    // Now resume our task.
686    m_task.Resume();
687}
688
689nub_break_t
690MachProcess::CreateBreakpoint(nub_addr_t addr, nub_size_t length, bool hardware, thread_t tid)
691{
692    DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::CreateBreakpoint ( addr = 0x%8.8llx, length = %llu, hardware = %i, tid = 0x%4.4x )", (uint64_t)addr, (uint64_t)length, hardware, tid);
693    if (hardware && tid == INVALID_NUB_THREAD)
694        tid = GetCurrentThread();
695
696    DNBBreakpoint bp(addr, length, tid, hardware);
697    nub_break_t breakID = m_breakpoints.Add(bp);
698    if (EnableBreakpoint(breakID))
699    {
700        DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::CreateBreakpoint ( addr = 0x%8.8llx, length = %llu, tid = 0x%4.4x ) => %u", (uint64_t)addr, (uint64_t)length, tid, breakID);
701        return breakID;
702    }
703    else
704    {
705        m_breakpoints.Remove(breakID);
706    }
707    // We failed to enable the breakpoint
708    return INVALID_NUB_BREAK_ID;
709}
710
711nub_watch_t
712MachProcess::CreateWatchpoint(nub_addr_t addr, nub_size_t length, uint32_t watch_flags, bool hardware, thread_t tid)
713{
714    DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::CreateWatchpoint ( addr = 0x%8.8llx, length = %llu, flags = 0x%8.8x, hardware = %i, tid = 0x%4.4x )", (uint64_t)addr, (uint64_t)length, watch_flags, hardware, tid);
715    if (hardware && tid == INVALID_NUB_THREAD)
716        tid = GetCurrentThread();
717
718    DNBBreakpoint watch(addr, length, tid, hardware);
719    watch.SetIsWatchpoint(watch_flags);
720
721    nub_watch_t watchID = m_watchpoints.Add(watch);
722    if (EnableWatchpoint(watchID))
723    {
724        DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::CreateWatchpoint ( addr = 0x%8.8llx, length = %llu, tid = 0x%x) => %u", (uint64_t)addr, (uint64_t)length, tid, watchID);
725        return watchID;
726    }
727    else
728    {
729        DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::CreateWatchpoint ( addr = 0x%8.8llx, length = %llu, tid = 0x%x) => FAILED (%u)", (uint64_t)addr, (uint64_t)length, tid, watchID);
730        m_watchpoints.Remove(watchID);
731    }
732    // We failed to enable the watchpoint
733    return INVALID_NUB_BREAK_ID;
734}
735
736nub_size_t
737MachProcess::DisableAllBreakpoints(bool remove)
738{
739    DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::%s (remove = %d )", __FUNCTION__, remove);
740    DNBBreakpoint *bp;
741    nub_size_t disabled_count = 0;
742    nub_size_t idx = 0;
743    while ((bp = m_breakpoints.GetByIndex(idx)) != NULL)
744    {
745        bool success = DisableBreakpoint(bp->GetID(), remove);
746
747        if (success)
748            disabled_count++;
749        // If we failed to disable the breakpoint or we aren't removing the breakpoint
750        // increment the breakpoint index. Otherwise DisableBreakpoint will have removed
751        // the breakpoint at this index and we don't need to change it.
752        if ((success == false) || (remove == false))
753            idx++;
754    }
755    return disabled_count;
756}
757
758nub_size_t
759MachProcess::DisableAllWatchpoints(bool remove)
760{
761    DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::%s (remove = %d )", __FUNCTION__, remove);
762    DNBBreakpoint *wp;
763    nub_size_t disabled_count = 0;
764    nub_size_t idx = 0;
765    while ((wp = m_watchpoints.GetByIndex(idx)) != NULL)
766    {
767        bool success = DisableWatchpoint(wp->GetID(), remove);
768
769        if (success)
770            disabled_count++;
771        // If we failed to disable the watchpoint or we aren't removing the watchpoint
772        // increment the watchpoint index. Otherwise DisableWatchpoint will have removed
773        // the watchpoint at this index and we don't need to change it.
774        if ((success == false) || (remove == false))
775            idx++;
776    }
777    return disabled_count;
778}
779
780bool
781MachProcess::DisableBreakpoint(nub_break_t breakID, bool remove)
782{
783    DNBBreakpoint *bp = m_breakpoints.FindByID (breakID);
784    if (bp)
785    {
786        nub_addr_t addr = bp->Address();
787        DNBLogThreadedIf(LOG_BREAKPOINTS | LOG_VERBOSE, "MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx", breakID, remove, (uint64_t)addr);
788
789        if (bp->IsHardware())
790        {
791            bool hw_disable_result = m_thread_list.DisableHardwareBreakpoint (bp);
792
793            if (hw_disable_result == true)
794            {
795                bp->SetEnabled(false);
796                // Let the thread list know that a breakpoint has been modified
797                if (remove)
798                {
799                    m_thread_list.NotifyBreakpointChanged(bp);
800                    m_breakpoints.Remove(breakID);
801                }
802                DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx (hardware) => success", breakID, remove, (uint64_t)addr);
803                return true;
804            }
805
806            return false;
807        }
808
809        const nub_size_t break_op_size = bp->ByteSize();
810        assert (break_op_size > 0);
811        const uint8_t * const break_op = DNBArchProtocol::GetBreakpointOpcode (bp->ByteSize());
812        if (break_op_size > 0)
813        {
814            // Clear a software breakoint instruction
815            uint8_t curr_break_op[break_op_size];
816            bool break_op_found = false;
817
818            // Read the breakpoint opcode
819            if (m_task.ReadMemory(addr, break_op_size, curr_break_op) == break_op_size)
820            {
821                bool verify = false;
822                if (bp->IsEnabled())
823                {
824                    // Make sure we have the a breakpoint opcode exists at this address
825                    if (memcmp(curr_break_op, break_op, break_op_size) == 0)
826                    {
827                        break_op_found = true;
828                        // We found a valid breakpoint opcode at this address, now restore
829                        // the saved opcode.
830                        if (m_task.WriteMemory(addr, break_op_size, bp->SavedOpcodeBytes()) == break_op_size)
831                        {
832                            verify = true;
833                        }
834                        else
835                        {
836                            DNBLogError("MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx memory write failed when restoring original opcode", breakID, remove, (uint64_t)addr);
837                        }
838                    }
839                    else
840                    {
841                        DNBLogWarning("MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx expected a breakpoint opcode but didn't find one.", breakID, remove, (uint64_t)addr);
842                        // Set verify to true and so we can check if the original opcode has already been restored
843                        verify = true;
844                    }
845                }
846                else
847                {
848                    DNBLogThreadedIf(LOG_BREAKPOINTS | LOG_VERBOSE, "MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx is not enabled", breakID, remove, (uint64_t)addr);
849                    // Set verify to true and so we can check if the original opcode is there
850                    verify = true;
851                }
852
853                if (verify)
854                {
855                    uint8_t verify_opcode[break_op_size];
856                    // Verify that our original opcode made it back to the inferior
857                    if (m_task.ReadMemory(addr, break_op_size, verify_opcode) == break_op_size)
858                    {
859                        // compare the memory we just read with the original opcode
860                        if (memcmp(bp->SavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
861                        {
862                            // SUCCESS
863                            bp->SetEnabled(false);
864                            // Let the thread list know that a breakpoint has been modified
865                            if (remove)
866                            {
867                                m_thread_list.NotifyBreakpointChanged(bp);
868                                m_breakpoints.Remove(breakID);
869                            }
870                            DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx => success", breakID, remove, (uint64_t)addr);
871                            return true;
872                        }
873                        else
874                        {
875                            if (break_op_found)
876                                DNBLogError("MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx: failed to restore original opcode", breakID, remove, (uint64_t)addr);
877                            else
878                                DNBLogError("MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx: opcode changed", breakID, remove, (uint64_t)addr);
879                        }
880                    }
881                    else
882                    {
883                        DNBLogWarning("MachProcess::DisableBreakpoint: unable to disable breakpoint 0x%8.8llx", (uint64_t)addr);
884                    }
885                }
886            }
887            else
888            {
889                DNBLogWarning("MachProcess::DisableBreakpoint: unable to read memory at 0x%8.8llx", (uint64_t)addr);
890            }
891        }
892    }
893    else
894    {
895        DNBLogError("MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) invalid breakpoint ID", breakID, remove);
896    }
897    return false;
898}
899
900bool
901MachProcess::DisableWatchpoint(nub_watch_t watchID, bool remove)
902{
903    DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::%s(watchID = %d, remove = %d)", __FUNCTION__, watchID, remove);
904    DNBBreakpoint *wp = m_watchpoints.FindByID (watchID);
905    if (wp)
906    {
907        nub_addr_t addr = wp->Address();
908        DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::DisableWatchpoint ( watchID = %d, remove = %d ) addr = 0x%8.8llx", watchID, remove, (uint64_t)addr);
909
910        if (wp->IsHardware())
911        {
912            bool hw_disable_result = m_thread_list.DisableHardwareWatchpoint (wp);
913
914            if (hw_disable_result == true)
915            {
916                wp->SetEnabled(false);
917                if (remove)
918                    m_watchpoints.Remove(watchID);
919                DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::Disablewatchpoint ( watchID = %d, remove = %d ) addr = 0x%8.8llx (hardware) => success", watchID, remove, (uint64_t)addr);
920                return true;
921            }
922        }
923
924        // TODO: clear software watchpoints if we implement them
925    }
926    else
927    {
928        DNBLogError("MachProcess::DisableWatchpoint ( watchID = %d, remove = %d ) invalid watchpoint ID", watchID, remove);
929    }
930    return false;
931}
932
933
934void
935MachProcess::DumpBreakpoint(nub_break_t breakID) const
936{
937    DNBLogThreaded("MachProcess::DumpBreakpoint(breakID = %d)", breakID);
938
939    if (NUB_BREAK_ID_IS_VALID(breakID))
940    {
941        const DNBBreakpoint *bp = m_breakpoints.FindByID(breakID);
942        if (bp)
943            bp->Dump();
944        else
945            DNBLog("MachProcess::DumpBreakpoint(breakID = %d): invalid breakID", breakID);
946    }
947    else
948    {
949        m_breakpoints.Dump();
950    }
951}
952
953void
954MachProcess::DumpWatchpoint(nub_watch_t watchID) const
955{
956    DNBLogThreaded("MachProcess::DumpWatchpoint(watchID = %d)", watchID);
957
958    if (NUB_BREAK_ID_IS_VALID(watchID))
959    {
960        const DNBBreakpoint *wp = m_watchpoints.FindByID(watchID);
961        if (wp)
962            wp->Dump();
963        else
964            DNBLog("MachProcess::DumpWatchpoint(watchID = %d): invalid watchID", watchID);
965    }
966    else
967    {
968        m_watchpoints.Dump();
969    }
970}
971
972uint32_t
973MachProcess::GetNumSupportedHardwareWatchpoints () const
974{
975    return m_thread_list.NumSupportedHardwareWatchpoints();
976}
977
978bool
979MachProcess::EnableBreakpoint(nub_break_t breakID)
980{
981    DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::EnableBreakpoint ( breakID = %d )", breakID);
982    DNBBreakpoint *bp = m_breakpoints.FindByID (breakID);
983    if (bp)
984    {
985        nub_addr_t addr = bp->Address();
986        if (bp->IsEnabled())
987        {
988            DNBLogWarning("MachProcess::EnableBreakpoint ( breakID = %d ) addr = 0x%8.8llx: breakpoint already enabled.", breakID, (uint64_t)addr);
989            return true;
990        }
991        else
992        {
993            if (bp->HardwarePreferred())
994            {
995                bp->SetHardwareIndex(m_thread_list.EnableHardwareBreakpoint(bp));
996                if (bp->IsHardware())
997                {
998                    bp->SetEnabled(true);
999                    return true;
1000                }
1001            }
1002
1003            const nub_size_t break_op_size = bp->ByteSize();
1004            assert (break_op_size != 0);
1005            const uint8_t * const break_op = DNBArchProtocol::GetBreakpointOpcode (break_op_size);
1006            if (break_op_size > 0)
1007            {
1008                // Save the original opcode by reading it
1009                if (m_task.ReadMemory(addr, break_op_size, bp->SavedOpcodeBytes()) == break_op_size)
1010                {
1011                    // Write a software breakpoint in place of the original opcode
1012                    if (m_task.WriteMemory(addr, break_op_size, break_op) == break_op_size)
1013                    {
1014                        uint8_t verify_break_op[4];
1015                        if (m_task.ReadMemory(addr, break_op_size, verify_break_op) == break_op_size)
1016                        {
1017                            if (memcmp(break_op, verify_break_op, break_op_size) == 0)
1018                            {
1019                                bp->SetEnabled(true);
1020                                // Let the thread list know that a breakpoint has been modified
1021                                m_thread_list.NotifyBreakpointChanged(bp);
1022                                DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::EnableBreakpoint ( breakID = %d ) addr = 0x%8.8llx: SUCCESS.", breakID, (uint64_t)addr);
1023                                return true;
1024                            }
1025                            else
1026                            {
1027                                DNBLogError("MachProcess::EnableBreakpoint ( breakID = %d ) addr = 0x%8.8llx: breakpoint opcode verification failed.", breakID, (uint64_t)addr);
1028                            }
1029                        }
1030                        else
1031                        {
1032                            DNBLogError("MachProcess::EnableBreakpoint ( breakID = %d ) addr = 0x%8.8llx: unable to read memory to verify breakpoint opcode.", breakID, (uint64_t)addr);
1033                        }
1034                    }
1035                    else
1036                    {
1037                        DNBLogError("MachProcess::EnableBreakpoint ( breakID = %d ) addr = 0x%8.8llx: unable to write breakpoint opcode to memory.", breakID, (uint64_t)addr);
1038                    }
1039                }
1040                else
1041                {
1042                    DNBLogError("MachProcess::EnableBreakpoint ( breakID = %d ) addr = 0x%8.8llx: unable to read memory at breakpoint address.", breakID, (uint64_t)addr);
1043                }
1044            }
1045            else
1046            {
1047                DNBLogError("MachProcess::EnableBreakpoint ( breakID = %d ) no software breakpoint opcode for current architecture.", breakID);
1048            }
1049        }
1050    }
1051    return false;
1052}
1053
1054bool
1055MachProcess::EnableWatchpoint(nub_watch_t watchID)
1056{
1057    DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::EnableWatchpoint(watchID = %d)", watchID);
1058    DNBBreakpoint *wp = m_watchpoints.FindByID (watchID);
1059    if (wp)
1060    {
1061        nub_addr_t addr = wp->Address();
1062        if (wp->IsEnabled())
1063        {
1064            DNBLogWarning("MachProcess::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1065            return true;
1066        }
1067        else
1068        {
1069            // Currently only try and set hardware watchpoints.
1070            wp->SetHardwareIndex(m_thread_list.EnableHardwareWatchpoint(wp));
1071            if (wp->IsHardware())
1072            {
1073                wp->SetEnabled(true);
1074                return true;
1075            }
1076            // TODO: Add software watchpoints by doing page protection tricks.
1077        }
1078    }
1079    return false;
1080}
1081
1082// Called by the exception thread when an exception has been received from
1083// our process. The exception message is completely filled and the exception
1084// data has already been copied.
1085void
1086MachProcess::ExceptionMessageReceived (const MachException::Message& exceptionMessage)
1087{
1088    PTHREAD_MUTEX_LOCKER (locker, m_exception_messages_mutex);
1089
1090    if (m_exception_messages.empty())
1091        m_task.Suspend();
1092
1093    DNBLogThreadedIf(LOG_EXCEPTIONS, "MachProcess::ExceptionMessageReceived ( )");
1094
1095    // Use a locker to automatically unlock our mutex in case of exceptions
1096    // Add the exception to our internal exception stack
1097    m_exception_messages.push_back(exceptionMessage);
1098}
1099
1100void
1101MachProcess::ExceptionMessageBundleComplete()
1102{
1103    // We have a complete bundle of exceptions for our child process.
1104    PTHREAD_MUTEX_LOCKER (locker, m_exception_messages_mutex);
1105    DNBLogThreadedIf(LOG_EXCEPTIONS, "%s: %llu exception messages.", __PRETTY_FUNCTION__, (uint64_t)m_exception_messages.size());
1106    if (!m_exception_messages.empty())
1107    {
1108        // Let all threads recover from stopping and do any clean up based
1109        // on the previous thread state (if any).
1110        m_thread_list.ProcessDidStop(this);
1111
1112        // Let each thread know of any exceptions
1113        task_t task = m_task.TaskPort();
1114        size_t i;
1115        for (i=0; i<m_exception_messages.size(); ++i)
1116        {
1117            // Let the thread list figure use the MachProcess to forward all exceptions
1118            // on down to each thread.
1119            if (m_exception_messages[i].state.task_port == task)
1120                m_thread_list.NotifyException(m_exception_messages[i].state);
1121            if (DNBLogCheckLogBit(LOG_EXCEPTIONS))
1122                m_exception_messages[i].Dump();
1123        }
1124
1125        if (DNBLogCheckLogBit(LOG_THREAD))
1126            m_thread_list.Dump();
1127
1128        bool step_more = false;
1129        if (m_thread_list.ShouldStop(step_more))
1130        {
1131            // Wait for the eEventProcessRunningStateChanged event to be reset
1132            // before changing state to stopped to avoid race condition with
1133            // very fast start/stops
1134            struct timespec timeout;
1135            //DNBTimer::OffsetTimeOfDay(&timeout, 0, 250 * 1000);   // Wait for 250 ms
1136            DNBTimer::OffsetTimeOfDay(&timeout, 1, 0);  // Wait for 250 ms
1137            m_events.WaitForEventsToReset(eEventProcessRunningStateChanged, &timeout);
1138            SetState(eStateStopped);
1139        }
1140        else
1141        {
1142            // Resume without checking our current state.
1143            PrivateResume ();
1144        }
1145    }
1146    else
1147    {
1148        DNBLogThreadedIf(LOG_EXCEPTIONS, "%s empty exception messages bundle (%llu exceptions).", __PRETTY_FUNCTION__, (uint64_t)m_exception_messages.size());
1149    }
1150}
1151
1152nub_size_t
1153MachProcess::CopyImageInfos ( struct DNBExecutableImageInfo **image_infos, bool only_changed)
1154{
1155    if (m_image_infos_callback != NULL)
1156        return m_image_infos_callback(ProcessID(), image_infos, only_changed, m_image_infos_baton);
1157    return 0;
1158}
1159
1160void
1161MachProcess::SharedLibrariesUpdated ( )
1162{
1163    uint32_t event_bits = eEventSharedLibsStateChange;
1164    // Set the shared library event bit to let clients know of shared library
1165    // changes
1166    m_events.SetEvents(event_bits);
1167    // Wait for the event bit to reset if a reset ACK is requested
1168    m_events.WaitForResetAck(event_bits);
1169}
1170
1171void
1172MachProcess::AppendSTDOUT (char* s, size_t len)
1173{
1174    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (<%llu> %s) ...", __FUNCTION__, (uint64_t)len, s);
1175    PTHREAD_MUTEX_LOCKER (locker, m_stdio_mutex);
1176    m_stdout_data.append(s, len);
1177    m_events.SetEvents(eEventStdioAvailable);
1178
1179    // Wait for the event bit to reset if a reset ACK is requested
1180    m_events.WaitForResetAck(eEventStdioAvailable);
1181}
1182
1183size_t
1184MachProcess::GetAvailableSTDOUT (char *buf, size_t buf_size)
1185{
1186    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (&%p[%llu]) ...", __FUNCTION__, buf, (uint64_t)buf_size);
1187    PTHREAD_MUTEX_LOCKER (locker, m_stdio_mutex);
1188    size_t bytes_available = m_stdout_data.size();
1189    if (bytes_available > 0)
1190    {
1191        if (bytes_available > buf_size)
1192        {
1193            memcpy(buf, m_stdout_data.data(), buf_size);
1194            m_stdout_data.erase(0, buf_size);
1195            bytes_available = buf_size;
1196        }
1197        else
1198        {
1199            memcpy(buf, m_stdout_data.data(), bytes_available);
1200            m_stdout_data.clear();
1201        }
1202    }
1203    return bytes_available;
1204}
1205
1206nub_addr_t
1207MachProcess::GetDYLDAllImageInfosAddress ()
1208{
1209    DNBError err;
1210    return m_task.GetDYLDAllImageInfosAddress(err);
1211}
1212
1213size_t
1214MachProcess::GetAvailableSTDERR (char *buf, size_t buf_size)
1215{
1216    return 0;
1217}
1218
1219void *
1220MachProcess::STDIOThread(void *arg)
1221{
1222    MachProcess *proc = (MachProcess*) arg;
1223    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( arg = %p ) thread starting...", __FUNCTION__, arg);
1224
1225    // We start use a base and more options so we can control if we
1226    // are currently using a timeout on the mach_msg. We do this to get a
1227    // bunch of related exceptions on our exception port so we can process
1228    // then together. When we have multiple threads, we can get an exception
1229    // per thread and they will come in consecutively. The main thread loop
1230    // will start by calling mach_msg to without having the MACH_RCV_TIMEOUT
1231    // flag set in the options, so we will wait forever for an exception on
1232    // our exception port. After we get one exception, we then will use the
1233    // MACH_RCV_TIMEOUT option with a zero timeout to grab all other current
1234    // exceptions for our process. After we have received the last pending
1235    // exception, we will get a timeout which enables us to then notify
1236    // our main thread that we have an exception bundle avaiable. We then wait
1237    // for the main thread to tell this exception thread to start trying to get
1238    // exceptions messages again and we start again with a mach_msg read with
1239    // infinite timeout.
1240    DNBError err;
1241    int stdout_fd = proc->GetStdoutFileDescriptor();
1242    int stderr_fd = proc->GetStderrFileDescriptor();
1243    if (stdout_fd == stderr_fd)
1244        stderr_fd = -1;
1245
1246    while (stdout_fd >= 0 || stderr_fd >= 0)
1247    {
1248        ::pthread_testcancel ();
1249
1250        fd_set read_fds;
1251        FD_ZERO (&read_fds);
1252        if (stdout_fd >= 0)
1253            FD_SET (stdout_fd, &read_fds);
1254        if (stderr_fd >= 0)
1255            FD_SET (stderr_fd, &read_fds);
1256        int nfds = std::max<int>(stdout_fd, stderr_fd) + 1;
1257
1258        int num_set_fds = select (nfds, &read_fds, NULL, NULL, NULL);
1259        DNBLogThreadedIf(LOG_PROCESS, "select (nfds, &read_fds, NULL, NULL, NULL) => %d", num_set_fds);
1260
1261        if (num_set_fds < 0)
1262        {
1263            int select_errno = errno;
1264            if (DNBLogCheckLogBit(LOG_PROCESS))
1265            {
1266                err.SetError (select_errno, DNBError::POSIX);
1267                err.LogThreadedIfError("select (nfds, &read_fds, NULL, NULL, NULL) => %d", num_set_fds);
1268            }
1269
1270            switch (select_errno)
1271            {
1272            case EAGAIN:    // The kernel was (perhaps temporarily) unable to allocate the requested number of file descriptors, or we have non-blocking IO
1273                break;
1274            case EBADF:     // One of the descriptor sets specified an invalid descriptor.
1275                return NULL;
1276                break;
1277            case EINTR:     // A signal was delivered before the time limit expired and before any of the selected events occurred.
1278            case EINVAL:    // The specified time limit is invalid. One of its components is negative or too large.
1279            default:        // Other unknown error
1280                break;
1281            }
1282        }
1283        else if (num_set_fds == 0)
1284        {
1285        }
1286        else
1287        {
1288            char s[1024];
1289            s[sizeof(s)-1] = '\0';  // Ensure we have NULL termination
1290            int bytes_read = 0;
1291            if (stdout_fd >= 0 && FD_ISSET (stdout_fd, &read_fds))
1292            {
1293                do
1294                {
1295                    bytes_read = ::read (stdout_fd, s, sizeof(s)-1);
1296                    if (bytes_read < 0)
1297                    {
1298                        int read_errno = errno;
1299                        DNBLogThreadedIf(LOG_PROCESS, "read (stdout_fd, ) => %d   errno: %d (%s)", bytes_read, read_errno, strerror(read_errno));
1300                    }
1301                    else if (bytes_read == 0)
1302                    {
1303                        // EOF...
1304                        DNBLogThreadedIf(LOG_PROCESS, "read (stdout_fd, ) => %d  (reached EOF for child STDOUT)", bytes_read);
1305                        stdout_fd = -1;
1306                    }
1307                    else if (bytes_read > 0)
1308                    {
1309                        proc->AppendSTDOUT(s, bytes_read);
1310                    }
1311
1312                } while (bytes_read > 0);
1313            }
1314
1315            if (stderr_fd >= 0 && FD_ISSET (stderr_fd, &read_fds))
1316            {
1317                do
1318                {
1319                    bytes_read = ::read (stderr_fd, s, sizeof(s)-1);
1320                    if (bytes_read < 0)
1321                    {
1322                        int read_errno = errno;
1323                        DNBLogThreadedIf(LOG_PROCESS, "read (stderr_fd, ) => %d   errno: %d (%s)", bytes_read, read_errno, strerror(read_errno));
1324                    }
1325                    else if (bytes_read == 0)
1326                    {
1327                        // EOF...
1328                        DNBLogThreadedIf(LOG_PROCESS, "read (stderr_fd, ) => %d  (reached EOF for child STDERR)", bytes_read);
1329                        stderr_fd = -1;
1330                    }
1331                    else if (bytes_read > 0)
1332                    {
1333                        proc->AppendSTDOUT(s, bytes_read);
1334                    }
1335
1336                } while (bytes_read > 0);
1337            }
1338        }
1339    }
1340    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (%p): thread exiting...", __FUNCTION__, arg);
1341    return NULL;
1342}
1343
1344
1345void
1346MachProcess::SignalAsyncProfileData (const char *info)
1347{
1348    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (%s) ...", __FUNCTION__, info);
1349    PTHREAD_MUTEX_LOCKER (locker, m_profile_data_mutex);
1350    m_profile_data.append(info);
1351    m_events.SetEvents(eEventProfileDataAvailable);
1352
1353    // Wait for the event bit to reset if a reset ACK is requested
1354    m_events.WaitForResetAck(eEventProfileDataAvailable);
1355}
1356
1357
1358size_t
1359MachProcess::GetAsyncProfileData (char *buf, size_t buf_size)
1360{
1361    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (&%p[%llu]) ...", __FUNCTION__, buf, (uint64_t)buf_size);
1362    PTHREAD_MUTEX_LOCKER (locker, m_profile_data_mutex);
1363    size_t bytes_available = m_profile_data.size();
1364    if (bytes_available > 0)
1365    {
1366        if (bytes_available > buf_size)
1367        {
1368            memcpy(buf, m_profile_data.data(), buf_size);
1369            m_profile_data.erase(0, buf_size);
1370            bytes_available = buf_size;
1371        }
1372        else
1373        {
1374            memcpy(buf, m_profile_data.data(), bytes_available);
1375            m_profile_data.clear();
1376        }
1377    }
1378    return bytes_available;
1379}
1380
1381
1382void *
1383MachProcess::ProfileThread(void *arg)
1384{
1385    MachProcess *proc = (MachProcess*) arg;
1386    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( arg = %p ) thread starting...", __FUNCTION__, arg);
1387
1388    while (proc->IsProfilingEnabled())
1389    {
1390        nub_state_t state = proc->GetState();
1391        if (state == eStateRunning)
1392        {
1393            const char *data = proc->Task().GetProfileDataAsCString();
1394            if (data)
1395            {
1396                proc->SignalAsyncProfileData(data);
1397            }
1398        }
1399        else if ((state == eStateUnloaded) || (state == eStateDetached) || (state == eStateUnloaded))
1400        {
1401            // Done. Get out of this thread.
1402            break;
1403        }
1404
1405        // A simple way to set up the profile interval. We can also use select() or dispatch timer source if necessary.
1406        usleep(proc->ProfileInterval());
1407    }
1408    return NULL;
1409}
1410
1411
1412pid_t
1413MachProcess::AttachForDebug (pid_t pid, char *err_str, size_t err_len)
1414{
1415    // Clear out and clean up from any current state
1416    Clear();
1417    if (pid != 0)
1418    {
1419        DNBError err;
1420        // Make sure the process exists...
1421        if (::getpgid (pid) < 0)
1422        {
1423            err.SetErrorToErrno();
1424            const char *err_cstr = err.AsString();
1425            ::snprintf (err_str, err_len, "%s", err_cstr ? err_cstr : "No such process");
1426            return INVALID_NUB_PROCESS;
1427        }
1428
1429        SetState(eStateAttaching);
1430        m_pid = pid;
1431        // Let ourselves know we are going to be using SBS if the correct flag bit is set...
1432#ifdef WITH_SPRINGBOARD
1433        if (IsSBProcess(pid))
1434            m_flags |= eMachProcessFlagsUsingSBS;
1435#endif
1436        if (!m_task.StartExceptionThread(err))
1437        {
1438            const char *err_cstr = err.AsString();
1439            ::snprintf (err_str, err_len, "%s", err_cstr ? err_cstr : "unable to start the exception thread");
1440            DNBLogThreadedIf(LOG_PROCESS, "error: failed to attach to pid %d", pid);
1441            m_pid = INVALID_NUB_PROCESS;
1442            return INVALID_NUB_PROCESS;
1443        }
1444
1445        errno = 0;
1446        if (::ptrace (PT_ATTACHEXC, pid, 0, 0))
1447            err.SetError(errno);
1448        else
1449            err.Clear();
1450
1451        if (err.Success())
1452        {
1453            m_flags |= eMachProcessFlagsAttached;
1454            // Sleep a bit to let the exception get received and set our process status
1455            // to stopped.
1456            ::usleep(250000);
1457            DNBLogThreadedIf(LOG_PROCESS, "successfully attached to pid %d", pid);
1458            return m_pid;
1459        }
1460        else
1461        {
1462            ::snprintf (err_str, err_len, "%s", err.AsString());
1463            DNBLogThreadedIf(LOG_PROCESS, "error: failed to attach to pid %d", pid);
1464        }
1465    }
1466    return INVALID_NUB_PROCESS;
1467}
1468
1469// Do the process specific setup for attach.  If this returns NULL, then there's no
1470// platform specific stuff to be done to wait for the attach.  If you get non-null,
1471// pass that token to the CheckForProcess method, and then to CleanupAfterAttach.
1472
1473//  Call PrepareForAttach before attaching to a process that has not yet launched
1474// This returns a token that can be passed to CheckForProcess, and to CleanupAfterAttach.
1475// You should call CleanupAfterAttach to free the token, and do whatever other
1476// cleanup seems good.
1477
1478const void *
1479MachProcess::PrepareForAttach (const char *path, nub_launch_flavor_t launch_flavor, bool waitfor, DNBError &err_str)
1480{
1481#ifdef WITH_SPRINGBOARD
1482    // Tell SpringBoard to halt the next launch of this application on startup.
1483
1484    if (!waitfor)
1485        return NULL;
1486
1487    const char *app_ext = strstr(path, ".app");
1488    if (app_ext == NULL)
1489    {
1490        DNBLogThreadedIf(LOG_PROCESS, "MachProcess::PrepareForAttach(): path '%s' doesn't contain .app, we can't tell springboard to wait for launch...", path);
1491        return NULL;
1492    }
1493
1494    if (launch_flavor != eLaunchFlavorSpringBoard
1495        && launch_flavor != eLaunchFlavorDefault)
1496        return NULL;
1497
1498    std::string app_bundle_path(path, app_ext + strlen(".app"));
1499
1500    CFStringRef bundleIDCFStr = CopyBundleIDForPath (app_bundle_path.c_str (), err_str);
1501    std::string bundleIDStr;
1502    CFString::UTF8(bundleIDCFStr, bundleIDStr);
1503    DNBLogThreadedIf(LOG_PROCESS, "CopyBundleIDForPath (%s, err_str) returned @\"%s\"", app_bundle_path.c_str (), bundleIDStr.c_str());
1504
1505    if (bundleIDCFStr == NULL)
1506    {
1507        return NULL;
1508    }
1509
1510    SBSApplicationLaunchError sbs_error = 0;
1511
1512    const char *stdout_err = "/dev/null";
1513    CFString stdio_path;
1514    stdio_path.SetFileSystemRepresentation (stdout_err);
1515
1516    DNBLogThreadedIf(LOG_PROCESS, "SBSLaunchApplicationForDebugging ( @\"%s\" , NULL, NULL, NULL, @\"%s\", @\"%s\", SBSApplicationDebugOnNextLaunch | SBSApplicationLaunchWaitForDebugger )", bundleIDStr.c_str(), stdout_err, stdout_err);
1517    sbs_error = SBSLaunchApplicationForDebugging (bundleIDCFStr,
1518                                                  (CFURLRef)NULL,         // openURL
1519                                                  NULL, // launch_argv.get(),
1520                                                  NULL, // launch_envp.get(),  // CFDictionaryRef environment
1521                                                  stdio_path.get(),
1522                                                  stdio_path.get(),
1523                                                  SBSApplicationDebugOnNextLaunch | SBSApplicationLaunchWaitForDebugger);
1524
1525    if (sbs_error != SBSApplicationLaunchErrorSuccess)
1526    {
1527        err_str.SetError(sbs_error, DNBError::SpringBoard);
1528        return NULL;
1529    }
1530
1531    DNBLogThreadedIf(LOG_PROCESS, "Successfully set DebugOnNextLaunch.");
1532    return bundleIDCFStr;
1533# else
1534  return NULL;
1535#endif
1536}
1537
1538// Pass in the token you got from PrepareForAttach.  If there is a process
1539// for that token, then the pid will be returned, otherwise INVALID_NUB_PROCESS
1540// will be returned.
1541
1542nub_process_t
1543MachProcess::CheckForProcess (const void *attach_token)
1544{
1545    if (attach_token == NULL)
1546        return INVALID_NUB_PROCESS;
1547
1548#ifdef WITH_SPRINGBOARD
1549    CFStringRef bundleIDCFStr = (CFStringRef) attach_token;
1550    Boolean got_it;
1551    nub_process_t attach_pid;
1552    got_it = SBSProcessIDForDisplayIdentifier(bundleIDCFStr, &attach_pid);
1553    if (got_it)
1554        return attach_pid;
1555    else
1556        return INVALID_NUB_PROCESS;
1557#endif
1558    return INVALID_NUB_PROCESS;
1559}
1560
1561// Call this to clean up after you have either attached or given up on the attach.
1562// Pass true for success if you have attached, false if you have not.
1563// The token will also be freed at this point, so you can't use it after calling
1564// this method.
1565
1566void
1567MachProcess::CleanupAfterAttach (const void *attach_token, bool success, DNBError &err_str)
1568{
1569#ifdef WITH_SPRINGBOARD
1570    if (attach_token == NULL)
1571        return;
1572
1573    // Tell SpringBoard to cancel the debug on next launch of this application
1574    // if we failed to attach
1575    if (!success)
1576    {
1577        SBSApplicationLaunchError sbs_error = 0;
1578        CFStringRef bundleIDCFStr = (CFStringRef) attach_token;
1579
1580        sbs_error = SBSLaunchApplicationForDebugging (bundleIDCFStr,
1581                                                      (CFURLRef)NULL,
1582                                                      NULL,
1583                                                      NULL,
1584                                                      NULL,
1585                                                      NULL,
1586                                                      SBSApplicationCancelDebugOnNextLaunch);
1587
1588        if (sbs_error != SBSApplicationLaunchErrorSuccess)
1589        {
1590            err_str.SetError(sbs_error, DNBError::SpringBoard);
1591            return;
1592        }
1593    }
1594
1595    CFRelease((CFStringRef) attach_token);
1596#endif
1597}
1598
1599pid_t
1600MachProcess::LaunchForDebug
1601(
1602    const char *path,
1603    char const *argv[],
1604    char const *envp[],
1605    const char *working_directory, // NULL => dont' change, non-NULL => set working directory for inferior to this
1606    const char *stdin_path,
1607    const char *stdout_path,
1608    const char *stderr_path,
1609    bool no_stdio,
1610    nub_launch_flavor_t launch_flavor,
1611    int disable_aslr,
1612    DNBError &launch_err
1613)
1614{
1615    // Clear out and clean up from any current state
1616    Clear();
1617
1618    DNBLogThreadedIf(LOG_PROCESS, "%s( path = '%s', argv = %p, envp = %p, launch_flavor = %u, disable_aslr = %d )", __FUNCTION__, path, argv, envp, launch_flavor, disable_aslr);
1619
1620    // Fork a child process for debugging
1621    SetState(eStateLaunching);
1622
1623    switch (launch_flavor)
1624    {
1625    case eLaunchFlavorForkExec:
1626        m_pid = MachProcess::ForkChildForPTraceDebugging (path, argv, envp, this, launch_err);
1627        break;
1628
1629#ifdef WITH_SPRINGBOARD
1630
1631    case eLaunchFlavorSpringBoard:
1632        {
1633            const char *app_ext = strstr(path, ".app");
1634            if (app_ext && (app_ext[4] == '\0' || app_ext[4] == '/'))
1635            {
1636                std::string app_bundle_path(path, app_ext + strlen(".app"));
1637                if (SBLaunchForDebug (app_bundle_path.c_str(), argv, envp, no_stdio, launch_err) != 0)
1638                    return m_pid; // A successful SBLaunchForDebug() returns and assigns a non-zero m_pid.
1639                else
1640                    break; // We tried a springboard launch, but didn't succeed lets get out
1641            }
1642        }
1643        // In case the executable name has a ".app" fragment which confuses our debugserver,
1644        // let's do an intentional fallthrough here...
1645        launch_flavor = eLaunchFlavorPosixSpawn;
1646
1647#endif
1648
1649    case eLaunchFlavorPosixSpawn:
1650        m_pid = MachProcess::PosixSpawnChildForPTraceDebugging (path,
1651                                                                DNBArchProtocol::GetArchitecture (),
1652                                                                argv,
1653                                                                envp,
1654                                                                working_directory,
1655                                                                stdin_path,
1656                                                                stdout_path,
1657                                                                stderr_path,
1658                                                                no_stdio,
1659                                                                this,
1660                                                                disable_aslr,
1661                                                                launch_err);
1662        break;
1663
1664    default:
1665        // Invalid  launch
1666        launch_err.SetError(NUB_GENERIC_ERROR, DNBError::Generic);
1667        return INVALID_NUB_PROCESS;
1668    }
1669
1670    if (m_pid == INVALID_NUB_PROCESS)
1671    {
1672        // If we don't have a valid process ID and no one has set the error,
1673        // then return a generic error
1674        if (launch_err.Success())
1675            launch_err.SetError(NUB_GENERIC_ERROR, DNBError::Generic);
1676    }
1677    else
1678    {
1679        m_path = path;
1680        size_t i;
1681        char const *arg;
1682        for (i=0; (arg = argv[i]) != NULL; i++)
1683            m_args.push_back(arg);
1684
1685        m_task.StartExceptionThread(launch_err);
1686        if (launch_err.Fail())
1687        {
1688            if (launch_err.AsString() == NULL)
1689                launch_err.SetErrorString("unable to start the exception thread");
1690            ::ptrace (PT_KILL, m_pid, 0, 0);
1691            m_pid = INVALID_NUB_PROCESS;
1692            return INVALID_NUB_PROCESS;
1693        }
1694
1695        StartSTDIOThread();
1696
1697        if (launch_flavor == eLaunchFlavorPosixSpawn)
1698        {
1699
1700            SetState (eStateAttaching);
1701            errno = 0;
1702            int err = ::ptrace (PT_ATTACHEXC, m_pid, 0, 0);
1703            if (err == 0)
1704            {
1705                m_flags |= eMachProcessFlagsAttached;
1706                DNBLogThreadedIf(LOG_PROCESS, "successfully spawned pid %d", m_pid);
1707                launch_err.Clear();
1708            }
1709            else
1710            {
1711                SetState (eStateExited);
1712                DNBError ptrace_err(errno, DNBError::POSIX);
1713                DNBLogThreadedIf(LOG_PROCESS, "error: failed to attach to spawned pid %d (err = %i, errno = %i (%s))", m_pid, err, ptrace_err.Error(), ptrace_err.AsString());
1714                launch_err.SetError(NUB_GENERIC_ERROR, DNBError::Generic);
1715            }
1716        }
1717        else
1718        {
1719            launch_err.Clear();
1720        }
1721    }
1722    return m_pid;
1723}
1724
1725pid_t
1726MachProcess::PosixSpawnChildForPTraceDebugging
1727(
1728    const char *path,
1729    cpu_type_t cpu_type,
1730    char const *argv[],
1731    char const *envp[],
1732    const char *working_directory,
1733    const char *stdin_path,
1734    const char *stdout_path,
1735    const char *stderr_path,
1736    bool no_stdio,
1737    MachProcess* process,
1738    int disable_aslr,
1739    DNBError& err
1740)
1741{
1742    posix_spawnattr_t attr;
1743    short flags;
1744    DNBLogThreadedIf(LOG_PROCESS, "%s ( path='%s', argv=%p, envp=%p, working_dir=%s, stdin=%s, stdout=%s stderr=%s, no-stdio=%i)",
1745                     __FUNCTION__,
1746                     path,
1747                     argv,
1748                     envp,
1749                     working_directory,
1750                     stdin_path,
1751                     stdout_path,
1752                     stderr_path,
1753                     no_stdio);
1754
1755    err.SetError( ::posix_spawnattr_init (&attr), DNBError::POSIX);
1756    if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
1757        err.LogThreaded("::posix_spawnattr_init ( &attr )");
1758    if (err.Fail())
1759        return INVALID_NUB_PROCESS;
1760
1761    flags = POSIX_SPAWN_START_SUSPENDED | POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1762    if (disable_aslr)
1763        flags |= _POSIX_SPAWN_DISABLE_ASLR;
1764
1765    sigset_t no_signals;
1766    sigset_t all_signals;
1767    sigemptyset (&no_signals);
1768    sigfillset (&all_signals);
1769    ::posix_spawnattr_setsigmask(&attr, &no_signals);
1770    ::posix_spawnattr_setsigdefault(&attr, &all_signals);
1771
1772    err.SetError( ::posix_spawnattr_setflags (&attr, flags), DNBError::POSIX);
1773    if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
1774        err.LogThreaded("::posix_spawnattr_setflags ( &attr, POSIX_SPAWN_START_SUSPENDED%s )", flags & _POSIX_SPAWN_DISABLE_ASLR ? " | _POSIX_SPAWN_DISABLE_ASLR" : "");
1775    if (err.Fail())
1776        return INVALID_NUB_PROCESS;
1777
1778    // Don't do this on SnowLeopard, _sometimes_ the TASK_BASIC_INFO will fail
1779    // and we will fail to continue with our process...
1780
1781    // On SnowLeopard we should set "DYLD_NO_PIE" in the inferior environment....
1782
1783#if !defined(__arm__)
1784
1785    // We don't need to do this for ARM, and we really shouldn't now that we
1786    // have multiple CPU subtypes and no posix_spawnattr call that allows us
1787    // to set which CPU subtype to launch...
1788    if (cpu_type != 0)
1789    {
1790        size_t ocount = 0;
1791        err.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu_type, &ocount), DNBError::POSIX);
1792        if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
1793            err.LogThreaded("::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %llu )", cpu_type, (uint64_t)ocount);
1794
1795        if (err.Fail() != 0 || ocount != 1)
1796            return INVALID_NUB_PROCESS;
1797    }
1798#endif
1799
1800    PseudoTerminal pty;
1801
1802    posix_spawn_file_actions_t file_actions;
1803    err.SetError( ::posix_spawn_file_actions_init (&file_actions), DNBError::POSIX);
1804    int file_actions_valid = err.Success();
1805    if (!file_actions_valid || DNBLogCheckLogBit(LOG_PROCESS))
1806        err.LogThreaded("::posix_spawn_file_actions_init ( &file_actions )");
1807    int pty_error = -1;
1808    pid_t pid = INVALID_NUB_PROCESS;
1809    if (file_actions_valid)
1810    {
1811        if (stdin_path == NULL && stdout_path == NULL && stderr_path == NULL && !no_stdio)
1812        {
1813            pty_error = pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY);
1814            if (pty_error == PseudoTerminal::success)
1815            {
1816                stdin_path = stdout_path = stderr_path = pty.SlaveName();
1817            }
1818        }
1819
1820        // if no_stdio or std paths not supplied, then route to "/dev/null".
1821        if (no_stdio || stdin_path == NULL || stdin_path[0] == '\0')
1822            stdin_path = "/dev/null";
1823        if (no_stdio || stdout_path == NULL || stdout_path[0] == '\0')
1824            stdout_path = "/dev/null";
1825        if (no_stdio || stderr_path == NULL || stderr_path[0] == '\0')
1826            stderr_path = "/dev/null";
1827
1828        err.SetError( ::posix_spawn_file_actions_addopen (&file_actions,
1829                                                          STDIN_FILENO,
1830                                                          stdin_path,
1831                                                          O_RDONLY | O_NOCTTY,
1832                                                          0),
1833                     DNBError::POSIX);
1834        if (err.Fail() || DNBLogCheckLogBit (LOG_PROCESS))
1835            err.LogThreaded ("::posix_spawn_file_actions_addopen (&file_actions, filedes=STDIN_FILENO, path='%s')", stdin_path);
1836
1837        err.SetError( ::posix_spawn_file_actions_addopen (&file_actions,
1838                                                          STDOUT_FILENO,
1839                                                          stdout_path,
1840                                                          O_WRONLY | O_NOCTTY | O_CREAT,
1841                                                          0640),
1842                     DNBError::POSIX);
1843        if (err.Fail() || DNBLogCheckLogBit (LOG_PROCESS))
1844            err.LogThreaded ("::posix_spawn_file_actions_addopen (&file_actions, filedes=STDOUT_FILENO, path='%s')", stdout_path);
1845
1846        err.SetError( ::posix_spawn_file_actions_addopen (&file_actions,
1847                                                          STDERR_FILENO,
1848                                                          stderr_path,
1849                                                          O_WRONLY | O_NOCTTY | O_CREAT,
1850                                                          0640),
1851                     DNBError::POSIX);
1852        if (err.Fail() || DNBLogCheckLogBit (LOG_PROCESS))
1853            err.LogThreaded ("::posix_spawn_file_actions_addopen (&file_actions, filedes=STDERR_FILENO, path='%s')", stderr_path);
1854
1855        // TODO: Verify if we can set the working directory back immediately
1856        // after the posix_spawnp call without creating a race condition???
1857        if (working_directory)
1858            ::chdir (working_directory);
1859
1860        err.SetError( ::posix_spawnp (&pid, path, &file_actions, &attr, (char * const*)argv, (char * const*)envp), DNBError::POSIX);
1861        if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
1862            err.LogThreaded("::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )", pid, path, &file_actions, &attr, argv, envp);
1863    }
1864    else
1865    {
1866        // TODO: Verify if we can set the working directory back immediately
1867        // after the posix_spawnp call without creating a race condition???
1868        if (working_directory)
1869            ::chdir (working_directory);
1870
1871        err.SetError( ::posix_spawnp (&pid, path, NULL, &attr, (char * const*)argv, (char * const*)envp), DNBError::POSIX);
1872        if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
1873            err.LogThreaded("::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )", pid, path, NULL, &attr, argv, envp);
1874    }
1875
1876    // We have seen some cases where posix_spawnp was returning a valid
1877    // looking pid even when an error was returned, so clear it out
1878    if (err.Fail())
1879        pid = INVALID_NUB_PROCESS;
1880
1881    if (pty_error == 0)
1882    {
1883        if (process != NULL)
1884        {
1885            int master_fd = pty.ReleaseMasterFD();
1886            process->SetChildFileDescriptors(master_fd, master_fd, master_fd);
1887        }
1888    }
1889    ::posix_spawnattr_destroy (&attr);
1890
1891    if (pid != INVALID_NUB_PROCESS)
1892    {
1893        cpu_type_t pid_cpu_type = MachProcess::GetCPUTypeForLocalProcess (pid);
1894        DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( ) pid=%i, cpu_type=0x%8.8x", __FUNCTION__, pid, pid_cpu_type);
1895        if (pid_cpu_type)
1896            DNBArchProtocol::SetArchitecture (pid_cpu_type);
1897    }
1898
1899    if (file_actions_valid)
1900    {
1901        DNBError err2;
1902        err2.SetError( ::posix_spawn_file_actions_destroy (&file_actions), DNBError::POSIX);
1903        if (err2.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
1904            err2.LogThreaded("::posix_spawn_file_actions_destroy ( &file_actions )");
1905    }
1906
1907    return pid;
1908}
1909
1910uint32_t
1911MachProcess::GetCPUTypeForLocalProcess (pid_t pid)
1912{
1913    int mib[CTL_MAXNAME]={0,};
1914    size_t len = CTL_MAXNAME;
1915    if (::sysctlnametomib("sysctl.proc_cputype", mib, &len))
1916        return 0;
1917
1918    mib[len] = pid;
1919    len++;
1920
1921    cpu_type_t cpu;
1922    size_t cpu_len = sizeof(cpu);
1923    if (::sysctl (mib, len, &cpu, &cpu_len, 0, 0))
1924        cpu = 0;
1925    return cpu;
1926}
1927
1928pid_t
1929MachProcess::ForkChildForPTraceDebugging
1930(
1931    const char *path,
1932    char const *argv[],
1933    char const *envp[],
1934    MachProcess* process,
1935    DNBError& launch_err
1936)
1937{
1938    PseudoTerminal::Error pty_error = PseudoTerminal::success;
1939
1940    // Use a fork that ties the child process's stdin/out/err to a pseudo
1941    // terminal so we can read it in our MachProcess::STDIOThread
1942    // as unbuffered io.
1943    PseudoTerminal pty;
1944    pid_t pid = pty.Fork(pty_error);
1945
1946    if (pid < 0)
1947    {
1948        //--------------------------------------------------------------
1949        // Error during fork.
1950        //--------------------------------------------------------------
1951        return pid;
1952    }
1953    else if (pid == 0)
1954    {
1955        //--------------------------------------------------------------
1956        // Child process
1957        //--------------------------------------------------------------
1958        ::ptrace (PT_TRACE_ME, 0, 0, 0);    // Debug this process
1959        ::ptrace (PT_SIGEXC, 0, 0, 0);    // Get BSD signals as mach exceptions
1960
1961        // If our parent is setgid, lets make sure we don't inherit those
1962        // extra powers due to nepotism.
1963        if (::setgid (getgid ()) == 0)
1964        {
1965
1966            // Let the child have its own process group. We need to execute
1967            // this call in both the child and parent to avoid a race condition
1968            // between the two processes.
1969            ::setpgid (0, 0);    // Set the child process group to match its pid
1970
1971            // Sleep a bit to before the exec call
1972            ::sleep (1);
1973
1974            // Turn this process into
1975            ::execv (path, (char * const *)argv);
1976        }
1977        // Exit with error code. Child process should have taken
1978        // over in above exec call and if the exec fails it will
1979        // exit the child process below.
1980        ::exit (127);
1981    }
1982    else
1983    {
1984        //--------------------------------------------------------------
1985        // Parent process
1986        //--------------------------------------------------------------
1987        // Let the child have its own process group. We need to execute
1988        // this call in both the child and parent to avoid a race condition
1989        // between the two processes.
1990        ::setpgid (pid, pid);    // Set the child process group to match its pid
1991
1992        if (process != NULL)
1993        {
1994            // Release our master pty file descriptor so the pty class doesn't
1995            // close it and so we can continue to use it in our STDIO thread
1996            int master_fd = pty.ReleaseMasterFD();
1997            process->SetChildFileDescriptors(master_fd, master_fd, master_fd);
1998        }
1999    }
2000    return pid;
2001}
2002
2003#ifdef WITH_SPRINGBOARD
2004
2005pid_t
2006MachProcess::SBLaunchForDebug (const char *path, char const *argv[], char const *envp[], bool no_stdio, DNBError &launch_err)
2007{
2008    // Clear out and clean up from any current state
2009    Clear();
2010
2011    DNBLogThreadedIf(LOG_PROCESS, "%s( '%s', argv)", __FUNCTION__, path);
2012
2013    // Fork a child process for debugging
2014    SetState(eStateLaunching);
2015    m_pid = MachProcess::SBForkChildForPTraceDebugging(path, argv, envp, no_stdio, this, launch_err);
2016    if (m_pid != 0)
2017    {
2018        m_flags |= eMachProcessFlagsUsingSBS;
2019        m_path = path;
2020        size_t i;
2021        char const *arg;
2022        for (i=0; (arg = argv[i]) != NULL; i++)
2023            m_args.push_back(arg);
2024        m_task.StartExceptionThread(launch_err);
2025
2026        if (launch_err.Fail())
2027        {
2028            if (launch_err.AsString() == NULL)
2029                launch_err.SetErrorString("unable to start the exception thread");
2030            ::ptrace (PT_KILL, m_pid, 0, 0);
2031            m_pid = INVALID_NUB_PROCESS;
2032            return INVALID_NUB_PROCESS;
2033        }
2034
2035        StartSTDIOThread();
2036        SetState (eStateAttaching);
2037        int err = ::ptrace (PT_ATTACHEXC, m_pid, 0, 0);
2038        if (err == 0)
2039        {
2040            m_flags |= eMachProcessFlagsAttached;
2041            DNBLogThreadedIf(LOG_PROCESS, "successfully attached to pid %d", m_pid);
2042        }
2043        else
2044        {
2045            SetState (eStateExited);
2046            DNBLogThreadedIf(LOG_PROCESS, "error: failed to attach to pid %d", m_pid);
2047        }
2048    }
2049    return m_pid;
2050}
2051
2052#include <servers/bootstrap.h>
2053
2054// This returns a CFRetained pointer to the Bundle ID for app_bundle_path,
2055// or NULL if there was some problem getting the bundle id.
2056static CFStringRef
2057CopyBundleIDForPath (const char *app_bundle_path, DNBError &err_str)
2058{
2059    CFBundle bundle(app_bundle_path);
2060    CFStringRef bundleIDCFStr = bundle.GetIdentifier();
2061    std::string bundleID;
2062    if (CFString::UTF8(bundleIDCFStr, bundleID) == NULL)
2063    {
2064        struct stat app_bundle_stat;
2065        char err_msg[PATH_MAX];
2066
2067        if (::stat (app_bundle_path, &app_bundle_stat) < 0)
2068        {
2069            err_str.SetError(errno, DNBError::POSIX);
2070            snprintf(err_msg, sizeof(err_msg), "%s: \"%s\"", err_str.AsString(), app_bundle_path);
2071            err_str.SetErrorString(err_msg);
2072            DNBLogThreadedIf(LOG_PROCESS, "%s() error: %s", __FUNCTION__, err_msg);
2073        }
2074        else
2075        {
2076            err_str.SetError(-1, DNBError::Generic);
2077            snprintf(err_msg, sizeof(err_msg), "failed to extract CFBundleIdentifier from %s", app_bundle_path);
2078            err_str.SetErrorString(err_msg);
2079            DNBLogThreadedIf(LOG_PROCESS, "%s() error: failed to extract CFBundleIdentifier from '%s'", __FUNCTION__, app_bundle_path);
2080        }
2081        return NULL;
2082    }
2083
2084    DNBLogThreadedIf(LOG_PROCESS, "%s() extracted CFBundleIdentifier: %s", __FUNCTION__, bundleID.c_str());
2085    CFRetain (bundleIDCFStr);
2086
2087    return bundleIDCFStr;
2088}
2089
2090pid_t
2091MachProcess::SBForkChildForPTraceDebugging (const char *app_bundle_path, char const *argv[], char const *envp[], bool no_stdio, MachProcess* process, DNBError &launch_err)
2092{
2093    DNBLogThreadedIf(LOG_PROCESS, "%s( '%s', argv, %p)", __FUNCTION__, app_bundle_path, process);
2094    CFAllocatorRef alloc = kCFAllocatorDefault;
2095
2096    if (argv[0] == NULL)
2097        return INVALID_NUB_PROCESS;
2098
2099    size_t argc = 0;
2100    // Count the number of arguments
2101    while (argv[argc] != NULL)
2102        argc++;
2103
2104    // Enumerate the arguments
2105    size_t first_launch_arg_idx = 1;
2106    CFReleaser<CFMutableArrayRef> launch_argv;
2107
2108    if (argv[first_launch_arg_idx])
2109    {
2110        size_t launch_argc = argc > 0 ? argc - 1 : 0;
2111        launch_argv.reset (::CFArrayCreateMutable (alloc, launch_argc, &kCFTypeArrayCallBacks));
2112        size_t i;
2113        char const *arg;
2114        CFString launch_arg;
2115        for (i=first_launch_arg_idx; (i < argc) && ((arg = argv[i]) != NULL); i++)
2116        {
2117            launch_arg.reset(::CFStringCreateWithCString (alloc, arg, kCFStringEncodingUTF8));
2118            if (launch_arg.get() != NULL)
2119                CFArrayAppendValue(launch_argv.get(), launch_arg.get());
2120            else
2121                break;
2122        }
2123    }
2124
2125    // Next fill in the arguments dictionary.  Note, the envp array is of the form
2126    // Variable=value but SpringBoard wants a CF dictionary.  So we have to convert
2127    // this here.
2128
2129    CFReleaser<CFMutableDictionaryRef> launch_envp;
2130
2131    if (envp[0])
2132    {
2133        launch_envp.reset(::CFDictionaryCreateMutable(alloc, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
2134        const char *value;
2135        int name_len;
2136        CFString name_string, value_string;
2137
2138        for (int i = 0; envp[i] != NULL; i++)
2139        {
2140            value = strstr (envp[i], "=");
2141
2142            // If the name field is empty or there's no =, skip it.  Somebody's messing with us.
2143            if (value == NULL || value == envp[i])
2144                continue;
2145
2146            name_len = value - envp[i];
2147
2148            // Now move value over the "="
2149            value++;
2150
2151            name_string.reset(::CFStringCreateWithBytes(alloc, (const UInt8 *) envp[i], name_len, kCFStringEncodingUTF8, false));
2152            value_string.reset(::CFStringCreateWithCString(alloc, value, kCFStringEncodingUTF8));
2153            CFDictionarySetValue (launch_envp.get(), name_string.get(), value_string.get());
2154        }
2155    }
2156
2157    CFString stdio_path;
2158
2159    PseudoTerminal pty;
2160    if (!no_stdio)
2161    {
2162        PseudoTerminal::Error pty_err = pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY);
2163        if (pty_err == PseudoTerminal::success)
2164        {
2165            const char* slave_name = pty.SlaveName();
2166            DNBLogThreadedIf(LOG_PROCESS, "%s() successfully opened master pty, slave is %s", __FUNCTION__, slave_name);
2167            if (slave_name && slave_name[0])
2168            {
2169                ::chmod (slave_name, S_IRWXU | S_IRWXG | S_IRWXO);
2170                stdio_path.SetFileSystemRepresentation (slave_name);
2171            }
2172        }
2173    }
2174
2175    if (stdio_path.get() == NULL)
2176    {
2177        stdio_path.SetFileSystemRepresentation ("/dev/null");
2178    }
2179
2180    CFStringRef bundleIDCFStr = CopyBundleIDForPath (app_bundle_path, launch_err);
2181    if (bundleIDCFStr == NULL)
2182        return INVALID_NUB_PROCESS;
2183
2184    std::string bundleID;
2185    CFString::UTF8(bundleIDCFStr, bundleID);
2186
2187    CFData argv_data(NULL);
2188
2189    if (launch_argv.get())
2190    {
2191        if (argv_data.Serialize(launch_argv.get(), kCFPropertyListBinaryFormat_v1_0) == NULL)
2192        {
2193            DNBLogThreadedIf(LOG_PROCESS, "%s() error: failed to serialize launch arg array...", __FUNCTION__);
2194            return INVALID_NUB_PROCESS;
2195        }
2196    }
2197
2198    DNBLogThreadedIf(LOG_PROCESS, "%s() serialized launch arg array", __FUNCTION__);
2199
2200    // Find SpringBoard
2201    SBSApplicationLaunchError sbs_error = 0;
2202    sbs_error = SBSLaunchApplicationForDebugging (bundleIDCFStr,
2203                                                  (CFURLRef)NULL,         // openURL
2204                                                  launch_argv.get(),
2205                                                  launch_envp.get(),  // CFDictionaryRef environment
2206                                                  stdio_path.get(),
2207                                                  stdio_path.get(),
2208                                                  SBSApplicationLaunchWaitForDebugger | SBSApplicationLaunchUnlockDevice);
2209
2210
2211    launch_err.SetError(sbs_error, DNBError::SpringBoard);
2212
2213    if (sbs_error == SBSApplicationLaunchErrorSuccess)
2214    {
2215        static const useconds_t pid_poll_interval = 200000;
2216        static const useconds_t pid_poll_timeout = 30000000;
2217
2218        useconds_t pid_poll_total = 0;
2219
2220        nub_process_t pid = INVALID_NUB_PROCESS;
2221        Boolean pid_found = SBSProcessIDForDisplayIdentifier(bundleIDCFStr, &pid);
2222        // Poll until the process is running, as long as we are getting valid responses and the timeout hasn't expired
2223        // A return PID of 0 means the process is not running, which may be because it hasn't been (asynchronously) started
2224        // yet, or that it died very quickly (if you weren't using waitForDebugger).
2225        while (!pid_found && pid_poll_total < pid_poll_timeout)
2226        {
2227            usleep (pid_poll_interval);
2228            pid_poll_total += pid_poll_interval;
2229            DNBLogThreadedIf(LOG_PROCESS, "%s() polling Springboard for pid for %s...", __FUNCTION__, bundleID.c_str());
2230            pid_found = SBSProcessIDForDisplayIdentifier(bundleIDCFStr, &pid);
2231        }
2232
2233        CFRelease (bundleIDCFStr);
2234        if (pid_found)
2235        {
2236            if (process != NULL)
2237            {
2238                // Release our master pty file descriptor so the pty class doesn't
2239                // close it and so we can continue to use it in our STDIO thread
2240                int master_fd = pty.ReleaseMasterFD();
2241                process->SetChildFileDescriptors(master_fd, master_fd, master_fd);
2242            }
2243            DNBLogThreadedIf(LOG_PROCESS, "%s() => pid = %4.4x", __FUNCTION__, pid);
2244        }
2245        else
2246        {
2247            DNBLogError("failed to lookup the process ID for CFBundleIdentifier %s.", bundleID.c_str());
2248        }
2249        return pid;
2250    }
2251
2252    DNBLogError("unable to launch the application with CFBundleIdentifier '%s' sbs_error = %u", bundleID.c_str(), sbs_error);
2253    return INVALID_NUB_PROCESS;
2254}
2255
2256#endif // #ifdef WITH_SPRINGBOARD
2257
2258
2259