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