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