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