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