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