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