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