blob: cac5143f2834c88c374d309e92fa9acfd9fbe436 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- MachProcess.cpp -----------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Created by Greg Clayton on 6/15/07.
11//
12//===----------------------------------------------------------------------===//
13
14#include "DNB.h"
15#include <mach/mach.h>
Greg Clayton708c1ab2011-10-28 01:24:12 +000016#include <signal.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000017#include <spawn.h>
18#include <sys/fcntl.h>
19#include <sys/types.h>
20#include <sys/ptrace.h>
21#include <sys/stat.h>
Greg Clayton71337622011-02-24 22:24:29 +000022#include <sys/sysctl.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000023#include <unistd.h>
24#include "MacOSX/CFUtils.h"
25#include "SysSignal.h"
26
27#include <algorithm>
28#include <map>
29
30#include "DNBDataRef.h"
31#include "DNBLog.h"
32#include "DNBThreadResumeActions.h"
33#include "DNBTimer.h"
34#include "MachProcess.h"
35#include "PseudoTerminal.h"
36
37#include "CFBundle.h"
38#include "CFData.h"
39#include "CFString.h"
40
41static CFStringRef CopyBundleIDForPath (const char *app_buncle_path, DNBError &err_str);
42
Jason Molenda42999a42012-02-22 02:18:59 +000043#ifdef WITH_SPRINGBOARD
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044
45#include <CoreFoundation/CoreFoundation.h>
46#include <SpringBoardServices/SpringBoardServer.h>
47#include <SpringBoardServices/SBSWatchdogAssertion.h>
48
Chris Lattner30fdc8d2010-06-08 16:52:24 +000049static bool
50IsSBProcess (nub_process_t pid)
51{
Jim Ingham1bfe4f62012-07-24 01:23:53 +000052 CFReleaser<CFArrayRef> appIdsForPID (::SBSCopyDisplayIdentifiersForProcessID(pid));
53 return appIdsForPID.get() != NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000054}
55
Chris Lattner30fdc8d2010-06-08 16:52:24 +000056#endif
57
58#if 0
59#define DEBUG_LOG(fmt, ...) printf(fmt, ## __VA_ARGS__)
60#else
61#define DEBUG_LOG(fmt, ...)
62#endif
63
64#ifndef MACH_PROCESS_USE_POSIX_SPAWN
65#define MACH_PROCESS_USE_POSIX_SPAWN 1
66#endif
67
Greg Claytonf681b942010-08-31 18:35:14 +000068#ifndef _POSIX_SPAWN_DISABLE_ASLR
69#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
70#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000071
72MachProcess::MachProcess() :
73 m_pid (0),
Greg Clayton71337622011-02-24 22:24:29 +000074 m_cpu_type (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +000075 m_child_stdin (-1),
76 m_child_stdout (-1),
77 m_child_stderr (-1),
78 m_path (),
79 m_args (),
80 m_task (this),
81 m_flags (eMachProcessFlagsNone),
82 m_stdio_thread (0),
83 m_stdio_mutex (PTHREAD_MUTEX_RECURSIVE),
84 m_stdout_data (),
Greg Claytonc4e411f2011-01-18 19:36:39 +000085 m_thread_actions (),
Greg Clayton58d1c9a2010-10-18 04:14:23 +000086 m_thread_list (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +000087 m_exception_messages (),
88 m_exception_messages_mutex (PTHREAD_MUTEX_RECURSIVE),
Chris Lattner30fdc8d2010-06-08 16:52:24 +000089 m_state (eStateUnloaded),
90 m_state_mutex (PTHREAD_MUTEX_RECURSIVE),
91 m_events (0, kAllEventsMask),
92 m_breakpoints (),
93 m_watchpoints (),
94 m_name_to_addr_callback(NULL),
95 m_name_to_addr_baton(NULL),
96 m_image_infos_callback(NULL),
97 m_image_infos_baton(NULL)
98{
99 DNBLogThreadedIf(LOG_PROCESS | LOG_VERBOSE, "%s", __PRETTY_FUNCTION__);
100}
101
102MachProcess::~MachProcess()
103{
104 DNBLogThreadedIf(LOG_PROCESS | LOG_VERBOSE, "%s", __PRETTY_FUNCTION__);
105 Clear();
106}
107
108pid_t
109MachProcess::SetProcessID(pid_t pid)
110{
111 // Free any previous process specific data or resources
112 Clear();
113 // Set the current PID appropriately
114 if (pid == 0)
Johnny Chenc0cd18d2010-09-28 16:34:56 +0000115 m_pid = ::getpid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000116 else
117 m_pid = pid;
118 return m_pid; // Return actualy PID in case a zero pid was passed in
119}
120
121nub_state_t
122MachProcess::GetState()
123{
124 // If any other threads access this we will need a mutex for it
125 PTHREAD_MUTEX_LOCKER(locker, m_state_mutex);
126 return m_state;
127}
128
129const char *
130MachProcess::ThreadGetName(nub_thread_t tid)
131{
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000132 return m_thread_list.GetName(tid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000133}
134
135nub_state_t
136MachProcess::ThreadGetState(nub_thread_t tid)
137{
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000138 return m_thread_list.GetState(tid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000139}
140
141
142nub_size_t
143MachProcess::GetNumThreads () const
144{
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000145 return m_thread_list.NumThreads();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000146}
147
148nub_thread_t
149MachProcess::GetThreadAtIndex (nub_size_t thread_idx) const
150{
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000151 return m_thread_list.ThreadIDAtIndex(thread_idx);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000152}
153
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000154nub_thread_t
155MachProcess::GetCurrentThread ()
156{
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000157 return m_thread_list.CurrentThreadID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000158}
159
160nub_thread_t
161MachProcess::SetCurrentThread(nub_thread_t tid)
162{
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000163 return m_thread_list.SetCurrentThread(tid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000164}
165
166bool
167MachProcess::GetThreadStoppedReason(nub_thread_t tid, struct DNBThreadStopInfo *stop_info) const
168{
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000169 return m_thread_list.GetThreadStoppedReason(tid, stop_info);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000170}
171
172void
173MachProcess::DumpThreadStoppedReason(nub_thread_t tid) const
174{
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000175 return m_thread_list.DumpThreadStoppedReason(tid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000176}
177
178const char *
179MachProcess::GetThreadInfo(nub_thread_t tid) const
180{
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000181 return m_thread_list.GetThreadInfo(tid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000182}
183
Greg Clayton71337622011-02-24 22:24:29 +0000184uint32_t
185MachProcess::GetCPUType ()
186{
187 if (m_cpu_type == 0 && m_pid != 0)
188 m_cpu_type = MachProcess::GetCPUTypeForLocalProcess (m_pid);
189 return m_cpu_type;
190}
191
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000192const DNBRegisterSetInfo *
Greg Claytone2d4f0d2011-01-19 07:54:15 +0000193MachProcess::GetRegisterSetInfo (nub_thread_t tid, nub_size_t *num_reg_sets) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000194{
Greg Claytone2d4f0d2011-01-19 07:54:15 +0000195 MachThreadSP thread_sp (m_thread_list.GetThreadByID (tid));
196 if (thread_sp)
Greg Clayton3af9ea52010-11-18 05:57:03 +0000197 {
Greg Claytone2d4f0d2011-01-19 07:54:15 +0000198 DNBArchProtocol *arch = thread_sp->GetArchProtocol();
Greg Clayton3af9ea52010-11-18 05:57:03 +0000199 if (arch)
200 return arch->GetRegisterSetInfo (num_reg_sets);
201 }
202 *num_reg_sets = 0;
203 return NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000204}
205
206bool
207MachProcess::GetRegisterValue ( nub_thread_t tid, uint32_t set, uint32_t reg, DNBRegisterValue *value ) const
208{
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000209 return m_thread_list.GetRegisterValue(tid, set, reg, value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000210}
211
212bool
213MachProcess::SetRegisterValue ( nub_thread_t tid, uint32_t set, uint32_t reg, const DNBRegisterValue *value ) const
214{
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000215 return m_thread_list.SetRegisterValue(tid, set, reg, value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000216}
217
218void
219MachProcess::SetState(nub_state_t new_state)
220{
221 // If any other threads access this we will need a mutex for it
222 uint32_t event_mask = 0;
223
224 // Scope for mutex locker
225 {
226 PTHREAD_MUTEX_LOCKER(locker, m_state_mutex);
227 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::SetState ( %s )", DNBStateAsString(new_state));
228
229 const nub_state_t old_state = m_state;
230
231 if (old_state != new_state)
232 {
233 if (NUB_STATE_IS_STOPPED(new_state))
234 event_mask = eEventProcessStoppedStateChanged;
235 else
236 event_mask = eEventProcessRunningStateChanged;
237
238 m_state = new_state;
239 if (new_state == eStateStopped)
240 m_stop_count++;
241 }
242 }
243
244 if (event_mask != 0)
245 {
246 m_events.SetEvents (event_mask);
247
248 // Wait for the event bit to reset if a reset ACK is requested
249 m_events.WaitForResetAck(event_mask);
250 }
251
252}
253
254void
255MachProcess::Clear()
256{
257 // Clear any cached thread list while the pid and task are still valid
258
259 m_task.Clear();
260 // Now clear out all member variables
261 m_pid = INVALID_NUB_PROCESS;
262 CloseChildFileDescriptors();
263 m_path.clear();
264 m_args.clear();
265 SetState(eStateUnloaded);
266 m_flags = eMachProcessFlagsNone;
267 m_stop_count = 0;
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000268 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000269 {
270 PTHREAD_MUTEX_LOCKER(locker, m_exception_messages_mutex);
271 m_exception_messages.clear();
272 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000273}
274
275
276bool
277MachProcess::StartSTDIOThread()
278{
279 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( )", __FUNCTION__);
280 // Create the thread that watches for the child STDIO
Greg Clayton3382c2c2010-07-30 23:14:42 +0000281 return ::pthread_create (&m_stdio_thread, NULL, MachProcess::STDIOThread, this) == 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000282}
283
284
285nub_addr_t
286MachProcess::LookupSymbol(const char *name, const char *shlib)
287{
288 if (m_name_to_addr_callback != NULL && name && name[0])
289 return m_name_to_addr_callback(ProcessID(), name, shlib, m_name_to_addr_baton);
290 return INVALID_NUB_ADDRESS;
291}
292
293bool
294MachProcess::Resume (const DNBThreadResumeActions& thread_actions)
295{
296 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Resume ()");
297 nub_state_t state = GetState();
298
299 if (CanResume(state))
300 {
Greg Claytonc4e411f2011-01-18 19:36:39 +0000301 m_thread_actions = thread_actions;
302 PrivateResume();
Greg Clayton3382c2c2010-07-30 23:14:42 +0000303 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000304 }
305 else if (state == eStateRunning)
306 {
307 DNBLogThreadedIf(LOG_PROCESS, "Resume() - task 0x%x is running, ignoring...", m_task.TaskPort());
Greg Clayton3382c2c2010-07-30 23:14:42 +0000308 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000309 }
Greg Clayton3382c2c2010-07-30 23:14:42 +0000310 DNBLogThreadedIf(LOG_PROCESS, "Resume() - task 0x%x can't continue, ignoring...", m_task.TaskPort());
311 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000312}
313
314bool
315MachProcess::Kill (const struct timespec *timeout_abstime)
316{
317 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Kill ()");
Jim Ingham5d2735e2012-04-25 17:45:26 +0000318 nub_state_t state = DoSIGSTOP(true, false, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000319 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Kill() DoSIGSTOP() state = %s", DNBStateAsString(state));
320 errno = 0;
321 ::ptrace (PT_KILL, m_pid, 0, 0);
Greg Clayton3382c2c2010-07-30 23:14:42 +0000322 DNBError err;
323 err.SetErrorToErrno();
Greg Clayton490fbbe2011-10-28 22:59:14 +0000324 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Kill() DoSIGSTOP() ::ptrace (PT_KILL, pid=%u, 0, 0) => 0x%8.8x (%s)", m_pid, err.Error(), err.AsString());
Greg Claytonc4e411f2011-01-18 19:36:39 +0000325 m_thread_actions = DNBThreadResumeActions (eStateRunning, 0);
326 PrivateResume ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000327 return true;
328}
329
330bool
331MachProcess::Signal (int signal, const struct timespec *timeout_abstime)
332{
333 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Signal (signal = %d, timeout = %p)", signal, timeout_abstime);
334 nub_state_t state = GetState();
335 if (::kill (ProcessID(), signal) == 0)
336 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000337 // If we were running and we have a timeout, wait for the signal to stop
338 if (IsRunning(state) && timeout_abstime)
339 {
340 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Signal (signal = %d, timeout = %p) waiting for signal to stop process...", signal, timeout_abstime);
341 m_events.WaitForSetEvents(eEventProcessStoppedStateChanged, timeout_abstime);
342 state = GetState();
343 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Signal (signal = %d, timeout = %p) state = %s", signal, timeout_abstime, DNBStateAsString(state));
344 return !IsRunning (state);
345 }
346 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Signal (signal = %d, timeout = %p) not waiting...", signal, timeout_abstime);
Greg Clayton3382c2c2010-07-30 23:14:42 +0000347 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000348 }
Greg Clayton3382c2c2010-07-30 23:14:42 +0000349 DNBError err(errno, DNBError::POSIX);
350 err.LogThreadedIfError("kill (pid = %d, signo = %i)", ProcessID(), signal);
351 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000352
353}
354
355nub_state_t
Jim Ingham5d2735e2012-04-25 17:45:26 +0000356MachProcess::DoSIGSTOP (bool clear_bps_and_wps, bool allow_running, uint32_t *thread_idx_ptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000357{
358 nub_state_t state = GetState();
359 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::DoSIGSTOP() state = %s", DNBStateAsString (state));
360
361 if (!IsRunning(state))
362 {
363 if (clear_bps_and_wps)
364 {
365 DisableAllBreakpoints (true);
366 DisableAllWatchpoints (true);
367 clear_bps_and_wps = false;
368 }
369
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000370 // If we already have a thread stopped due to a SIGSTOP, we don't have
371 // to do anything...
Caroline Tice5d7be2e2010-11-02 16:16:53 +0000372 uint32_t thread_idx = m_thread_list.GetThreadIndexForThreadStoppedWithSignal (SIGSTOP);
373 if (thread_idx_ptr)
374 *thread_idx_ptr = thread_idx;
375 if (thread_idx != UINT32_MAX)
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000376 return GetState();
377
378 // No threads were stopped with a SIGSTOP, we need to run and halt the
379 // process with a signal
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000380 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::DoSIGSTOP() state = %s -- resuming process", DNBStateAsString (state));
Jim Ingham5d2735e2012-04-25 17:45:26 +0000381 if (allow_running)
382 m_thread_actions = DNBThreadResumeActions (eStateRunning, 0);
383 else
384 m_thread_actions = DNBThreadResumeActions (eStateSuspended, 0);
385
Greg Claytonc4e411f2011-01-18 19:36:39 +0000386 PrivateResume ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000387
388 // Reset the event that says we were indeed running
389 m_events.ResetEvents(eEventProcessRunningStateChanged);
390 state = GetState();
391 }
392
393 // We need to be stopped in order to be able to detach, so we need
394 // to send ourselves a SIGSTOP
395
396 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::DoSIGSTOP() state = %s -- sending SIGSTOP", DNBStateAsString (state));
397 struct timespec sigstop_timeout;
398 DNBTimer::OffsetTimeOfDay(&sigstop_timeout, 2, 0);
399 Signal (SIGSTOP, &sigstop_timeout);
400 if (clear_bps_and_wps)
401 {
402 DisableAllBreakpoints (true);
403 DisableAllWatchpoints (true);
Greg Clayton23f59502012-07-17 03:23:13 +0000404 //clear_bps_and_wps = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000405 }
Caroline Tice5d7be2e2010-11-02 16:16:53 +0000406 uint32_t thread_idx = m_thread_list.GetThreadIndexForThreadStoppedWithSignal (SIGSTOP);
407 if (thread_idx_ptr)
408 *thread_idx_ptr = thread_idx;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000409 return GetState();
410}
411
412bool
413MachProcess::Detach()
414{
415 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Detach()");
416
Caroline Tice5d7be2e2010-11-02 16:16:53 +0000417 uint32_t thread_idx = UINT32_MAX;
Jim Ingham5d2735e2012-04-25 17:45:26 +0000418 nub_state_t state = DoSIGSTOP(true, true, &thread_idx);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000419 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Detach() DoSIGSTOP() returned %s", DNBStateAsString(state));
420
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000421 {
Greg Claytonc4e411f2011-01-18 19:36:39 +0000422 m_thread_actions.Clear();
Caroline Tice5d7be2e2010-11-02 16:16:53 +0000423 DNBThreadResumeAction thread_action;
424 thread_action.tid = m_thread_list.ThreadIDAtIndex (thread_idx);
425 thread_action.state = eStateRunning;
426 thread_action.signal = -1;
427 thread_action.addr = INVALID_NUB_ADDRESS;
428
Greg Claytonc4e411f2011-01-18 19:36:39 +0000429 m_thread_actions.Append (thread_action);
430 m_thread_actions.SetDefaultThreadActionIfNeeded (eStateRunning, 0);
Caroline Tice5d7be2e2010-11-02 16:16:53 +0000431
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000432 PTHREAD_MUTEX_LOCKER (locker, m_exception_messages_mutex);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000433
Greg Claytonc4e411f2011-01-18 19:36:39 +0000434 ReplyToAllExceptions ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000435
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000436 }
437
438 m_task.ShutDownExcecptionThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000439
440 // Detach from our process
441 errno = 0;
442 nub_process_t pid = m_pid;
Caroline Tice5d7be2e2010-11-02 16:16:53 +0000443 int ret = ::ptrace (PT_DETACH, pid, (caddr_t)1, 0);
Greg Clayton3382c2c2010-07-30 23:14:42 +0000444 DNBError err(errno, DNBError::POSIX);
Caroline Tice5d7be2e2010-11-02 16:16:53 +0000445 if (DNBLogCheckLogBit(LOG_PROCESS) || err.Fail() || (ret != 0))
Greg Clayton3382c2c2010-07-30 23:14:42 +0000446 err.LogThreaded("::ptrace (PT_DETACH, %u, (caddr_t)1, 0)", pid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000447
448 // Resume our task
449 m_task.Resume();
450
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000451 // NULL our task out as we have already retored all exception ports
452 m_task.Clear();
453
454 // Clear out any notion of the process we once were
455 Clear();
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000456
457 SetState(eStateDetached);
458
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000459 return true;
460}
461
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000462nub_size_t
463MachProcess::RemoveTrapsFromBuffer (nub_addr_t addr, nub_size_t size, uint8_t *buf) const
464{
465 nub_size_t bytes_removed = 0;
466 const DNBBreakpoint *bp;
467 nub_addr_t intersect_addr;
468 nub_size_t intersect_size;
469 nub_size_t opcode_offset;
470 nub_size_t idx;
471 for (idx = 0; (bp = m_breakpoints.GetByIndex(idx)) != NULL; ++idx)
472 {
473 if (bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset))
474 {
475 assert(addr <= intersect_addr && intersect_addr < addr + size);
476 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
477 assert(opcode_offset + intersect_size <= bp->ByteSize());
478 nub_size_t buf_offset = intersect_addr - addr;
479 ::memcpy(buf + buf_offset, bp->SavedOpcodeBytes() + opcode_offset, intersect_size);
480 }
481 }
482 return bytes_removed;
483}
484
485//----------------------------------------------------------------------
486// ReadMemory from the MachProcess level will always remove any software
487// breakpoints from the memory buffer before returning. If you wish to
488// read memory and see those traps, read from the MachTask
489// (m_task.ReadMemory()) as that version will give you what is actually
490// in inferior memory.
491//----------------------------------------------------------------------
492nub_size_t
493MachProcess::ReadMemory (nub_addr_t addr, nub_size_t size, void *buf)
494{
495 // We need to remove any current software traps (enabled software
496 // breakpoints) that we may have placed in our tasks memory.
497
498 // First just read the memory as is
499 nub_size_t bytes_read = m_task.ReadMemory(addr, size, buf);
500
501 // Then place any opcodes that fall into this range back into the buffer
502 // before we return this to callers.
503 if (bytes_read > 0)
504 RemoveTrapsFromBuffer (addr, size, (uint8_t *)buf);
505 return bytes_read;
506}
507
508//----------------------------------------------------------------------
509// WriteMemory from the MachProcess level will always write memory around
510// any software breakpoints. Any software breakpoints will have their
511// opcodes modified if they are enabled. Any memory that doesn't overlap
512// with software breakpoints will be written to. If you wish to write to
513// inferior memory without this interference, then write to the MachTask
514// (m_task.WriteMemory()) as that version will always modify inferior
515// memory.
516//----------------------------------------------------------------------
517nub_size_t
518MachProcess::WriteMemory (nub_addr_t addr, nub_size_t size, const void *buf)
519{
520 // We need to write any data that would go where any current software traps
521 // (enabled software breakpoints) any software traps (breakpoints) that we
522 // may have placed in our tasks memory.
523
524 std::map<nub_addr_t, DNBBreakpoint *> addr_to_bp_map;
525 DNBBreakpoint *bp;
526 nub_size_t idx;
527 for (idx = 0; (bp = m_breakpoints.GetByIndex(idx)) != NULL; ++idx)
528 {
529 if (bp->IntersectsRange(addr, size, NULL, NULL, NULL))
530 addr_to_bp_map[bp->Address()] = bp;
531 }
532
533 // If we don't have any software breakpoints that are in this buffer, then
534 // we can just write memory and be done with it.
535 if (addr_to_bp_map.empty())
536 return m_task.WriteMemory(addr, size, buf);
537
538 // If we make it here, we have some breakpoints that overlap and we need
539 // to work around them.
540
541 nub_size_t bytes_written = 0;
542 nub_addr_t intersect_addr;
543 nub_size_t intersect_size;
544 nub_size_t opcode_offset;
545 const uint8_t *ubuf = (const uint8_t *)buf;
546 std::map<nub_addr_t, DNBBreakpoint *>::iterator pos, end = addr_to_bp_map.end();
547 for (pos = addr_to_bp_map.begin(); pos != end; ++pos)
548 {
549 bp = pos->second;
550
551 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
552 assert(addr <= intersect_addr && intersect_addr < addr + size);
553 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
554 assert(opcode_offset + intersect_size <= bp->ByteSize());
555
556 // Check for bytes before this breakpoint
557 const nub_addr_t curr_addr = addr + bytes_written;
558 if (intersect_addr > curr_addr)
559 {
560 // There are some bytes before this breakpoint that we need to
561 // just write to memory
562 nub_size_t curr_size = intersect_addr - curr_addr;
563 nub_size_t curr_bytes_written = m_task.WriteMemory(curr_addr, curr_size, ubuf + bytes_written);
564 bytes_written += curr_bytes_written;
565 if (curr_bytes_written != curr_size)
566 {
567 // We weren't able to write all of the requested bytes, we
568 // are done looping and will return the number of bytes that
569 // we have written so far.
570 break;
571 }
572 }
573
574 // Now write any bytes that would cover up any software breakpoints
575 // directly into the breakpoint opcode buffer
576 ::memcpy(bp->SavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
577 bytes_written += intersect_size;
578 }
579
580 // Write any remaining bytes after the last breakpoint if we have any left
581 if (bytes_written < size)
582 bytes_written += m_task.WriteMemory(addr + bytes_written, size - bytes_written, ubuf + bytes_written);
583
584 return bytes_written;
585}
586
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000587void
Greg Claytonc4e411f2011-01-18 19:36:39 +0000588MachProcess::ReplyToAllExceptions ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000589{
590 PTHREAD_MUTEX_LOCKER(locker, m_exception_messages_mutex);
591 if (m_exception_messages.empty() == false)
592 {
593 MachException::Message::iterator pos;
594 MachException::Message::iterator begin = m_exception_messages.begin();
595 MachException::Message::iterator end = m_exception_messages.end();
596 for (pos = begin; pos != end; ++pos)
597 {
Greg Clayton490fbbe2011-10-28 22:59:14 +0000598 DNBLogThreadedIf(LOG_EXCEPTIONS, "Replying to exception %u...", (uint32_t)std::distance(begin, pos));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000599 int thread_reply_signal = 0;
600
Greg Claytonc4e411f2011-01-18 19:36:39 +0000601 const DNBThreadResumeAction *action = m_thread_actions.GetActionForThread (pos->state.thread_port, false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000602
603 if (action)
604 {
605 thread_reply_signal = action->signal;
606 if (thread_reply_signal)
Greg Claytonc4e411f2011-01-18 19:36:39 +0000607 m_thread_actions.SetSignalHandledForThread (pos->state.thread_port);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000608 }
609
Greg Clayton3382c2c2010-07-30 23:14:42 +0000610 DNBError err (pos->Reply(this, thread_reply_signal));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000611 if (DNBLogCheckLogBit(LOG_EXCEPTIONS))
Greg Clayton3382c2c2010-07-30 23:14:42 +0000612 err.LogThreadedIfError("Error replying to exception");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000613 }
614
615 // Erase all exception message as we should have used and replied
616 // to them all already.
617 m_exception_messages.clear();
618 }
619}
620void
Greg Claytonc4e411f2011-01-18 19:36:39 +0000621MachProcess::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000622{
623 PTHREAD_MUTEX_LOCKER (locker, m_exception_messages_mutex);
624
Greg Claytonc4e411f2011-01-18 19:36:39 +0000625 ReplyToAllExceptions ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000626// bool stepOverBreakInstruction = step;
627
628 // Let the thread prepare to resume and see if any threads want us to
629 // step over a breakpoint instruction (ProcessWillResume will modify
630 // the value of stepOverBreakInstruction).
Greg Claytonc4e411f2011-01-18 19:36:39 +0000631 m_thread_list.ProcessWillResume (this, m_thread_actions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000632
633 // Set our state accordingly
Greg Claytonc4e411f2011-01-18 19:36:39 +0000634 if (m_thread_actions.NumActionsWithState(eStateStepping))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000635 SetState (eStateStepping);
636 else
637 SetState (eStateRunning);
638
639 // Now resume our task.
Greg Clayton3382c2c2010-07-30 23:14:42 +0000640 m_task.Resume();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000641}
642
643nub_break_t
644MachProcess::CreateBreakpoint(nub_addr_t addr, nub_size_t length, bool hardware, thread_t tid)
645{
Greg Clayton490fbbe2011-10-28 22:59:14 +0000646 DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::CreateBreakpoint ( addr = 0x%8.8llx, length = %zu, hardware = %i, tid = 0x%4.4x )", (uint64_t)addr, length, hardware, tid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000647 if (hardware && tid == INVALID_NUB_THREAD)
648 tid = GetCurrentThread();
649
650 DNBBreakpoint bp(addr, length, tid, hardware);
651 nub_break_t breakID = m_breakpoints.Add(bp);
652 if (EnableBreakpoint(breakID))
653 {
Greg Clayton490fbbe2011-10-28 22:59:14 +0000654 DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::CreateBreakpoint ( addr = 0x%8.8llx, length = %zu, tid = 0x%4.4x ) => %u", (uint64_t)addr, length, tid, breakID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000655 return breakID;
656 }
657 else
658 {
659 m_breakpoints.Remove(breakID);
660 }
661 // We failed to enable the breakpoint
662 return INVALID_NUB_BREAK_ID;
663}
664
665nub_watch_t
666MachProcess::CreateWatchpoint(nub_addr_t addr, nub_size_t length, uint32_t watch_flags, bool hardware, thread_t tid)
667{
Greg Clayton490fbbe2011-10-28 22:59:14 +0000668 DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::CreateWatchpoint ( addr = 0x%8.8llx, length = %zu, flags = 0x%8.8x, hardware = %i, tid = 0x%4.4x )", (uint64_t)addr, length, watch_flags, hardware, tid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000669 if (hardware && tid == INVALID_NUB_THREAD)
670 tid = GetCurrentThread();
671
672 DNBBreakpoint watch(addr, length, tid, hardware);
673 watch.SetIsWatchpoint(watch_flags);
674
675 nub_watch_t watchID = m_watchpoints.Add(watch);
676 if (EnableWatchpoint(watchID))
677 {
Greg Clayton490fbbe2011-10-28 22:59:14 +0000678 DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::CreateWatchpoint ( addr = 0x%8.8llx, length = %zu, tid = 0x%x) => %u", (uint64_t)addr, length, tid, watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000679 return watchID;
680 }
681 else
682 {
Greg Clayton490fbbe2011-10-28 22:59:14 +0000683 DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::CreateWatchpoint ( addr = 0x%8.8llx, length = %zu, tid = 0x%x) => FAILED (%u)", (uint64_t)addr, length, tid, watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000684 m_watchpoints.Remove(watchID);
685 }
686 // We failed to enable the watchpoint
687 return INVALID_NUB_BREAK_ID;
688}
689
690nub_size_t
691MachProcess::DisableAllBreakpoints(bool remove)
692{
693 DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::%s (remove = %d )", __FUNCTION__, remove);
694 DNBBreakpoint *bp;
695 nub_size_t disabled_count = 0;
696 nub_size_t idx = 0;
697 while ((bp = m_breakpoints.GetByIndex(idx)) != NULL)
698 {
699 bool success = DisableBreakpoint(bp->GetID(), remove);
700
701 if (success)
702 disabled_count++;
703 // If we failed to disable the breakpoint or we aren't removing the breakpoint
704 // increment the breakpoint index. Otherwise DisableBreakpoint will have removed
705 // the breakpoint at this index and we don't need to change it.
706 if ((success == false) || (remove == false))
707 idx++;
708 }
709 return disabled_count;
710}
711
712nub_size_t
713MachProcess::DisableAllWatchpoints(bool remove)
714{
715 DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::%s (remove = %d )", __FUNCTION__, remove);
716 DNBBreakpoint *wp;
717 nub_size_t disabled_count = 0;
718 nub_size_t idx = 0;
719 while ((wp = m_watchpoints.GetByIndex(idx)) != NULL)
720 {
721 bool success = DisableWatchpoint(wp->GetID(), remove);
722
723 if (success)
724 disabled_count++;
725 // If we failed to disable the watchpoint or we aren't removing the watchpoint
726 // increment the watchpoint index. Otherwise DisableWatchpoint will have removed
727 // the watchpoint at this index and we don't need to change it.
728 if ((success == false) || (remove == false))
729 idx++;
730 }
731 return disabled_count;
732}
733
734bool
735MachProcess::DisableBreakpoint(nub_break_t breakID, bool remove)
736{
737 DNBBreakpoint *bp = m_breakpoints.FindByID (breakID);
738 if (bp)
739 {
740 nub_addr_t addr = bp->Address();
741 DNBLogThreadedIf(LOG_BREAKPOINTS | LOG_VERBOSE, "MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx", breakID, remove, (uint64_t)addr);
742
743 if (bp->IsHardware())
744 {
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000745 bool hw_disable_result = m_thread_list.DisableHardwareBreakpoint (bp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000746
747 if (hw_disable_result == true)
748 {
749 bp->SetEnabled(false);
750 // Let the thread list know that a breakpoint has been modified
751 if (remove)
752 {
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000753 m_thread_list.NotifyBreakpointChanged(bp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000754 m_breakpoints.Remove(breakID);
755 }
756 DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx (hardware) => success", breakID, remove, (uint64_t)addr);
757 return true;
758 }
759
760 return false;
761 }
762
763 const nub_size_t break_op_size = bp->ByteSize();
764 assert (break_op_size > 0);
Greg Clayton3af9ea52010-11-18 05:57:03 +0000765 const uint8_t * const break_op = DNBArchProtocol::GetBreakpointOpcode (bp->ByteSize());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000766 if (break_op_size > 0)
767 {
768 // Clear a software breakoint instruction
769 uint8_t curr_break_op[break_op_size];
770 bool break_op_found = false;
771
772 // Read the breakpoint opcode
773 if (m_task.ReadMemory(addr, break_op_size, curr_break_op) == break_op_size)
774 {
775 bool verify = false;
776 if (bp->IsEnabled())
777 {
778 // Make sure we have the a breakpoint opcode exists at this address
779 if (memcmp(curr_break_op, break_op, break_op_size) == 0)
780 {
781 break_op_found = true;
782 // We found a valid breakpoint opcode at this address, now restore
783 // the saved opcode.
784 if (m_task.WriteMemory(addr, break_op_size, bp->SavedOpcodeBytes()) == break_op_size)
785 {
786 verify = true;
787 }
788 else
789 {
790 DNBLogError("MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx memory write failed when restoring original opcode", breakID, remove, (uint64_t)addr);
791 }
792 }
793 else
794 {
795 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);
796 // Set verify to true and so we can check if the original opcode has already been restored
797 verify = true;
798 }
799 }
800 else
801 {
Greg Claytondce502e2011-11-04 03:34:56 +0000802 DNBLogThreadedIf(LOG_BREAKPOINTS | LOG_VERBOSE, "MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx is not enabled", breakID, remove, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000803 // Set verify to true and so we can check if the original opcode is there
804 verify = true;
805 }
806
807 if (verify)
808 {
809 uint8_t verify_opcode[break_op_size];
810 // Verify that our original opcode made it back to the inferior
811 if (m_task.ReadMemory(addr, break_op_size, verify_opcode) == break_op_size)
812 {
813 // compare the memory we just read with the original opcode
814 if (memcmp(bp->SavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
815 {
816 // SUCCESS
817 bp->SetEnabled(false);
818 // Let the thread list know that a breakpoint has been modified
819 if (remove)
820 {
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000821 m_thread_list.NotifyBreakpointChanged(bp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000822 m_breakpoints.Remove(breakID);
823 }
824 DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx => success", breakID, remove, (uint64_t)addr);
825 return true;
826 }
827 else
828 {
829 if (break_op_found)
830 DNBLogError("MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx: failed to restore original opcode", breakID, remove, (uint64_t)addr);
831 else
832 DNBLogError("MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx: opcode changed", breakID, remove, (uint64_t)addr);
833 }
834 }
835 else
836 {
837 DNBLogWarning("MachProcess::DisableBreakpoint: unable to disable breakpoint 0x%8.8llx", (uint64_t)addr);
838 }
839 }
840 }
841 else
842 {
843 DNBLogWarning("MachProcess::DisableBreakpoint: unable to read memory at 0x%8.8llx", (uint64_t)addr);
844 }
845 }
846 }
847 else
848 {
849 DNBLogError("MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) invalid breakpoint ID", breakID, remove);
850 }
851 return false;
852}
853
854bool
855MachProcess::DisableWatchpoint(nub_watch_t watchID, bool remove)
856{
857 DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::%s(watchID = %d, remove = %d)", __FUNCTION__, watchID, remove);
858 DNBBreakpoint *wp = m_watchpoints.FindByID (watchID);
859 if (wp)
860 {
861 nub_addr_t addr = wp->Address();
862 DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::DisableWatchpoint ( watchID = %d, remove = %d ) addr = 0x%8.8llx", watchID, remove, (uint64_t)addr);
863
864 if (wp->IsHardware())
865 {
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000866 bool hw_disable_result = m_thread_list.DisableHardwareWatchpoint (wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000867
868 if (hw_disable_result == true)
869 {
870 wp->SetEnabled(false);
871 if (remove)
872 m_watchpoints.Remove(watchID);
873 DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::Disablewatchpoint ( watchID = %d, remove = %d ) addr = 0x%8.8llx (hardware) => success", watchID, remove, (uint64_t)addr);
874 return true;
875 }
876 }
877
878 // TODO: clear software watchpoints if we implement them
879 }
880 else
881 {
882 DNBLogError("MachProcess::DisableWatchpoint ( watchID = %d, remove = %d ) invalid watchpoint ID", watchID, remove);
883 }
884 return false;
885}
886
887
888void
889MachProcess::DumpBreakpoint(nub_break_t breakID) const
890{
891 DNBLogThreaded("MachProcess::DumpBreakpoint(breakID = %d)", breakID);
892
893 if (NUB_BREAK_ID_IS_VALID(breakID))
894 {
895 const DNBBreakpoint *bp = m_breakpoints.FindByID(breakID);
896 if (bp)
897 bp->Dump();
898 else
899 DNBLog("MachProcess::DumpBreakpoint(breakID = %d): invalid breakID", breakID);
900 }
901 else
902 {
903 m_breakpoints.Dump();
904 }
905}
906
907void
908MachProcess::DumpWatchpoint(nub_watch_t watchID) const
909{
910 DNBLogThreaded("MachProcess::DumpWatchpoint(watchID = %d)", watchID);
911
912 if (NUB_BREAK_ID_IS_VALID(watchID))
913 {
914 const DNBBreakpoint *wp = m_watchpoints.FindByID(watchID);
915 if (wp)
916 wp->Dump();
917 else
918 DNBLog("MachProcess::DumpWatchpoint(watchID = %d): invalid watchID", watchID);
919 }
920 else
921 {
922 m_watchpoints.Dump();
923 }
924}
925
Johnny Chen64637202012-05-23 21:09:52 +0000926uint32_t
927MachProcess::GetNumSupportedHardwareWatchpoints () const
928{
929 return m_thread_list.NumSupportedHardwareWatchpoints();
930}
931
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000932bool
933MachProcess::EnableBreakpoint(nub_break_t breakID)
934{
935 DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::EnableBreakpoint ( breakID = %d )", breakID);
936 DNBBreakpoint *bp = m_breakpoints.FindByID (breakID);
937 if (bp)
938 {
939 nub_addr_t addr = bp->Address();
940 if (bp->IsEnabled())
941 {
942 DNBLogWarning("MachProcess::EnableBreakpoint ( breakID = %d ) addr = 0x%8.8llx: breakpoint already enabled.", breakID, (uint64_t)addr);
943 return true;
944 }
945 else
946 {
947 if (bp->HardwarePreferred())
948 {
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000949 bp->SetHardwareIndex(m_thread_list.EnableHardwareBreakpoint(bp));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000950 if (bp->IsHardware())
951 {
952 bp->SetEnabled(true);
953 return true;
954 }
955 }
956
957 const nub_size_t break_op_size = bp->ByteSize();
958 assert (break_op_size != 0);
Greg Clayton3af9ea52010-11-18 05:57:03 +0000959 const uint8_t * const break_op = DNBArchProtocol::GetBreakpointOpcode (break_op_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000960 if (break_op_size > 0)
961 {
962 // Save the original opcode by reading it
963 if (m_task.ReadMemory(addr, break_op_size, bp->SavedOpcodeBytes()) == break_op_size)
964 {
965 // Write a software breakpoint in place of the original opcode
966 if (m_task.WriteMemory(addr, break_op_size, break_op) == break_op_size)
967 {
968 uint8_t verify_break_op[4];
969 if (m_task.ReadMemory(addr, break_op_size, verify_break_op) == break_op_size)
970 {
971 if (memcmp(break_op, verify_break_op, break_op_size) == 0)
972 {
973 bp->SetEnabled(true);
974 // Let the thread list know that a breakpoint has been modified
Greg Clayton58d1c9a2010-10-18 04:14:23 +0000975 m_thread_list.NotifyBreakpointChanged(bp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000976 DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::EnableBreakpoint ( breakID = %d ) addr = 0x%8.8llx: SUCCESS.", breakID, (uint64_t)addr);
977 return true;
978 }
979 else
980 {
981 DNBLogError("MachProcess::EnableBreakpoint ( breakID = %d ) addr = 0x%8.8llx: breakpoint opcode verification failed.", breakID, (uint64_t)addr);
982 }
983 }
984 else
985 {
986 DNBLogError("MachProcess::EnableBreakpoint ( breakID = %d ) addr = 0x%8.8llx: unable to read memory to verify breakpoint opcode.", breakID, (uint64_t)addr);
987 }
988 }
989 else
990 {
991 DNBLogError("MachProcess::EnableBreakpoint ( breakID = %d ) addr = 0x%8.8llx: unable to write breakpoint opcode to memory.", breakID, (uint64_t)addr);
992 }
993 }
994 else
995 {
996 DNBLogError("MachProcess::EnableBreakpoint ( breakID = %d ) addr = 0x%8.8llx: unable to read memory at breakpoint address.", breakID, (uint64_t)addr);
997 }
998 }
999 else
1000 {
1001 DNBLogError("MachProcess::EnableBreakpoint ( breakID = %d ) no software breakpoint opcode for current architecture.", breakID);
1002 }
1003 }
1004 }
1005 return false;
1006}
1007
1008bool
1009MachProcess::EnableWatchpoint(nub_watch_t watchID)
1010{
1011 DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::EnableWatchpoint(watchID = %d)", watchID);
1012 DNBBreakpoint *wp = m_watchpoints.FindByID (watchID);
1013 if (wp)
1014 {
1015 nub_addr_t addr = wp->Address();
1016 if (wp->IsEnabled())
1017 {
1018 DNBLogWarning("MachProcess::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1019 return true;
1020 }
1021 else
1022 {
1023 // Currently only try and set hardware watchpoints.
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001024 wp->SetHardwareIndex(m_thread_list.EnableHardwareWatchpoint(wp));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001025 if (wp->IsHardware())
1026 {
1027 wp->SetEnabled(true);
1028 return true;
1029 }
1030 // TODO: Add software watchpoints by doing page protection tricks.
1031 }
1032 }
1033 return false;
1034}
1035
1036// Called by the exception thread when an exception has been received from
1037// our process. The exception message is completely filled and the exception
1038// data has already been copied.
1039void
1040MachProcess::ExceptionMessageReceived (const MachException::Message& exceptionMessage)
1041{
1042 PTHREAD_MUTEX_LOCKER (locker, m_exception_messages_mutex);
1043
1044 if (m_exception_messages.empty())
1045 m_task.Suspend();
1046
1047 DNBLogThreadedIf(LOG_EXCEPTIONS, "MachProcess::ExceptionMessageReceived ( )");
1048
1049 // Use a locker to automatically unlock our mutex in case of exceptions
1050 // Add the exception to our internal exception stack
1051 m_exception_messages.push_back(exceptionMessage);
1052}
1053
1054void
1055MachProcess::ExceptionMessageBundleComplete()
1056{
1057 // We have a complete bundle of exceptions for our child process.
1058 PTHREAD_MUTEX_LOCKER (locker, m_exception_messages_mutex);
Greg Clayton490fbbe2011-10-28 22:59:14 +00001059 DNBLogThreadedIf(LOG_EXCEPTIONS, "%s: %zu exception messages.", __PRETTY_FUNCTION__, m_exception_messages.size());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001060 if (!m_exception_messages.empty())
1061 {
1062 // Let all threads recover from stopping and do any clean up based
1063 // on the previous thread state (if any).
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001064 m_thread_list.ProcessDidStop(this);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001065
1066 // Let each thread know of any exceptions
1067 task_t task = m_task.TaskPort();
1068 size_t i;
1069 for (i=0; i<m_exception_messages.size(); ++i)
1070 {
1071 // Let the thread list figure use the MachProcess to forward all exceptions
1072 // on down to each thread.
1073 if (m_exception_messages[i].state.task_port == task)
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001074 m_thread_list.NotifyException(m_exception_messages[i].state);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001075 if (DNBLogCheckLogBit(LOG_EXCEPTIONS))
1076 m_exception_messages[i].Dump();
1077 }
1078
1079 if (DNBLogCheckLogBit(LOG_THREAD))
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001080 m_thread_list.Dump();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001081
1082 bool step_more = false;
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001083 if (m_thread_list.ShouldStop(step_more))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001084 {
1085 // Wait for the eEventProcessRunningStateChanged event to be reset
1086 // before changing state to stopped to avoid race condition with
1087 // very fast start/stops
1088 struct timespec timeout;
1089 //DNBTimer::OffsetTimeOfDay(&timeout, 0, 250 * 1000); // Wait for 250 ms
1090 DNBTimer::OffsetTimeOfDay(&timeout, 1, 0); // Wait for 250 ms
1091 m_events.WaitForEventsToReset(eEventProcessRunningStateChanged, &timeout);
1092 SetState(eStateStopped);
1093 }
1094 else
1095 {
1096 // Resume without checking our current state.
Greg Claytonc4e411f2011-01-18 19:36:39 +00001097 PrivateResume ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001098 }
1099 }
1100 else
1101 {
Greg Claytondce502e2011-11-04 03:34:56 +00001102 DNBLogThreadedIf(LOG_EXCEPTIONS, "%s empty exception messages bundle (%zu exceptions).", __PRETTY_FUNCTION__, m_exception_messages.size());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001103 }
1104}
1105
1106nub_size_t
1107MachProcess::CopyImageInfos ( struct DNBExecutableImageInfo **image_infos, bool only_changed)
1108{
1109 if (m_image_infos_callback != NULL)
1110 return m_image_infos_callback(ProcessID(), image_infos, only_changed, m_image_infos_baton);
1111 return 0;
1112}
1113
1114void
1115MachProcess::SharedLibrariesUpdated ( )
1116{
1117 uint32_t event_bits = eEventSharedLibsStateChange;
1118 // Set the shared library event bit to let clients know of shared library
1119 // changes
1120 m_events.SetEvents(event_bits);
1121 // Wait for the event bit to reset if a reset ACK is requested
1122 m_events.WaitForResetAck(event_bits);
1123}
1124
1125void
1126MachProcess::AppendSTDOUT (char* s, size_t len)
1127{
Greg Clayton490fbbe2011-10-28 22:59:14 +00001128 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (<%zu> %s) ...", __FUNCTION__, len, s);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001129 PTHREAD_MUTEX_LOCKER (locker, m_stdio_mutex);
1130 m_stdout_data.append(s, len);
1131 m_events.SetEvents(eEventStdioAvailable);
1132
1133 // Wait for the event bit to reset if a reset ACK is requested
1134 m_events.WaitForResetAck(eEventStdioAvailable);
1135}
1136
1137size_t
1138MachProcess::GetAvailableSTDOUT (char *buf, size_t buf_size)
1139{
Greg Clayton490fbbe2011-10-28 22:59:14 +00001140 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (&%p[%zu]) ...", __FUNCTION__, buf, buf_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001141 PTHREAD_MUTEX_LOCKER (locker, m_stdio_mutex);
1142 size_t bytes_available = m_stdout_data.size();
1143 if (bytes_available > 0)
1144 {
1145 if (bytes_available > buf_size)
1146 {
1147 memcpy(buf, m_stdout_data.data(), buf_size);
1148 m_stdout_data.erase(0, buf_size);
1149 bytes_available = buf_size;
1150 }
1151 else
1152 {
1153 memcpy(buf, m_stdout_data.data(), bytes_available);
1154 m_stdout_data.clear();
1155 }
1156 }
1157 return bytes_available;
1158}
1159
1160nub_addr_t
1161MachProcess::GetDYLDAllImageInfosAddress ()
1162{
Greg Clayton3382c2c2010-07-30 23:14:42 +00001163 DNBError err;
1164 return m_task.GetDYLDAllImageInfosAddress(err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001165}
1166
1167size_t
1168MachProcess::GetAvailableSTDERR (char *buf, size_t buf_size)
1169{
1170 return 0;
1171}
1172
1173void *
1174MachProcess::STDIOThread(void *arg)
1175{
1176 MachProcess *proc = (MachProcess*) arg;
1177 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( arg = %p ) thread starting...", __FUNCTION__, arg);
1178
1179 // We start use a base and more options so we can control if we
1180 // are currently using a timeout on the mach_msg. We do this to get a
1181 // bunch of related exceptions on our exception port so we can process
1182 // then together. When we have multiple threads, we can get an exception
1183 // per thread and they will come in consecutively. The main thread loop
1184 // will start by calling mach_msg to without having the MACH_RCV_TIMEOUT
1185 // flag set in the options, so we will wait forever for an exception on
1186 // our exception port. After we get one exception, we then will use the
1187 // MACH_RCV_TIMEOUT option with a zero timeout to grab all other current
1188 // exceptions for our process. After we have received the last pending
1189 // exception, we will get a timeout which enables us to then notify
1190 // our main thread that we have an exception bundle avaiable. We then wait
1191 // for the main thread to tell this exception thread to start trying to get
1192 // exceptions messages again and we start again with a mach_msg read with
1193 // infinite timeout.
1194 DNBError err;
1195 int stdout_fd = proc->GetStdoutFileDescriptor();
1196 int stderr_fd = proc->GetStderrFileDescriptor();
1197 if (stdout_fd == stderr_fd)
1198 stderr_fd = -1;
1199
1200 while (stdout_fd >= 0 || stderr_fd >= 0)
1201 {
1202 ::pthread_testcancel ();
1203
1204 fd_set read_fds;
1205 FD_ZERO (&read_fds);
1206 if (stdout_fd >= 0)
1207 FD_SET (stdout_fd, &read_fds);
1208 if (stderr_fd >= 0)
1209 FD_SET (stderr_fd, &read_fds);
1210 int nfds = std::max<int>(stdout_fd, stderr_fd) + 1;
1211
1212 int num_set_fds = select (nfds, &read_fds, NULL, NULL, NULL);
1213 DNBLogThreadedIf(LOG_PROCESS, "select (nfds, &read_fds, NULL, NULL, NULL) => %d", num_set_fds);
1214
1215 if (num_set_fds < 0)
1216 {
1217 int select_errno = errno;
1218 if (DNBLogCheckLogBit(LOG_PROCESS))
1219 {
1220 err.SetError (select_errno, DNBError::POSIX);
1221 err.LogThreadedIfError("select (nfds, &read_fds, NULL, NULL, NULL) => %d", num_set_fds);
1222 }
1223
1224 switch (select_errno)
1225 {
1226 case EAGAIN: // The kernel was (perhaps temporarily) unable to allocate the requested number of file descriptors, or we have non-blocking IO
1227 break;
1228 case EBADF: // One of the descriptor sets specified an invalid descriptor.
1229 return NULL;
1230 break;
1231 case EINTR: // A signal was delivered before the time limit expired and before any of the selected events occurred.
1232 case EINVAL: // The specified time limit is invalid. One of its components is negative or too large.
1233 default: // Other unknown error
1234 break;
1235 }
1236 }
1237 else if (num_set_fds == 0)
1238 {
1239 }
1240 else
1241 {
1242 char s[1024];
1243 s[sizeof(s)-1] = '\0'; // Ensure we have NULL termination
1244 int bytes_read = 0;
1245 if (stdout_fd >= 0 && FD_ISSET (stdout_fd, &read_fds))
1246 {
1247 do
1248 {
1249 bytes_read = ::read (stdout_fd, s, sizeof(s)-1);
1250 if (bytes_read < 0)
1251 {
1252 int read_errno = errno;
1253 DNBLogThreadedIf(LOG_PROCESS, "read (stdout_fd, ) => %d errno: %d (%s)", bytes_read, read_errno, strerror(read_errno));
1254 }
1255 else if (bytes_read == 0)
1256 {
1257 // EOF...
1258 DNBLogThreadedIf(LOG_PROCESS, "read (stdout_fd, ) => %d (reached EOF for child STDOUT)", bytes_read);
1259 stdout_fd = -1;
1260 }
1261 else if (bytes_read > 0)
1262 {
1263 proc->AppendSTDOUT(s, bytes_read);
1264 }
1265
1266 } while (bytes_read > 0);
1267 }
1268
1269 if (stderr_fd >= 0 && FD_ISSET (stderr_fd, &read_fds))
1270 {
1271 do
1272 {
1273 bytes_read = ::read (stderr_fd, s, sizeof(s)-1);
1274 if (bytes_read < 0)
1275 {
1276 int read_errno = errno;
1277 DNBLogThreadedIf(LOG_PROCESS, "read (stderr_fd, ) => %d errno: %d (%s)", bytes_read, read_errno, strerror(read_errno));
1278 }
1279 else if (bytes_read == 0)
1280 {
1281 // EOF...
1282 DNBLogThreadedIf(LOG_PROCESS, "read (stderr_fd, ) => %d (reached EOF for child STDERR)", bytes_read);
1283 stderr_fd = -1;
1284 }
1285 else if (bytes_read > 0)
1286 {
1287 proc->AppendSTDOUT(s, bytes_read);
1288 }
1289
1290 } while (bytes_read > 0);
1291 }
1292 }
1293 }
1294 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (%p): thread exiting...", __FUNCTION__, arg);
1295 return NULL;
1296}
1297
1298pid_t
1299MachProcess::AttachForDebug (pid_t pid, char *err_str, size_t err_len)
1300{
1301 // Clear out and clean up from any current state
1302 Clear();
1303 if (pid != 0)
1304 {
Greg Clayton3382c2c2010-07-30 23:14:42 +00001305 DNBError err;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001306 // Make sure the process exists...
1307 if (::getpgid (pid) < 0)
1308 {
Greg Clayton3382c2c2010-07-30 23:14:42 +00001309 err.SetErrorToErrno();
1310 const char *err_cstr = err.AsString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001311 ::snprintf (err_str, err_len, "%s", err_cstr ? err_cstr : "No such process");
1312 return INVALID_NUB_PROCESS;
1313 }
1314
1315 SetState(eStateAttaching);
1316 m_pid = pid;
1317 // Let ourselves know we are going to be using SBS if the correct flag bit is set...
Jason Molenda42999a42012-02-22 02:18:59 +00001318#ifdef WITH_SPRINGBOARD
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001319 if (IsSBProcess(pid))
1320 m_flags |= eMachProcessFlagsUsingSBS;
1321#endif
Greg Clayton3382c2c2010-07-30 23:14:42 +00001322 if (!m_task.StartExceptionThread(err))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001323 {
Greg Clayton3382c2c2010-07-30 23:14:42 +00001324 const char *err_cstr = err.AsString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001325 ::snprintf (err_str, err_len, "%s", err_cstr ? err_cstr : "unable to start the exception thread");
1326 DNBLogThreadedIf(LOG_PROCESS, "error: failed to attach to pid %d", pid);
1327 m_pid = INVALID_NUB_PROCESS;
1328 return INVALID_NUB_PROCESS;
1329 }
1330
1331 errno = 0;
Greg Clayton3382c2c2010-07-30 23:14:42 +00001332 if (::ptrace (PT_ATTACHEXC, pid, 0, 0))
1333 err.SetError(errno);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001334 else
Greg Clayton3382c2c2010-07-30 23:14:42 +00001335 err.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001336
Greg Clayton3382c2c2010-07-30 23:14:42 +00001337 if (err.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001338 {
1339 m_flags |= eMachProcessFlagsAttached;
1340 // Sleep a bit to let the exception get received and set our process status
1341 // to stopped.
1342 ::usleep(250000);
1343 DNBLogThreadedIf(LOG_PROCESS, "successfully attached to pid %d", pid);
1344 return m_pid;
1345 }
1346 else
1347 {
Greg Clayton3382c2c2010-07-30 23:14:42 +00001348 ::snprintf (err_str, err_len, "%s", err.AsString());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001349 DNBLogThreadedIf(LOG_PROCESS, "error: failed to attach to pid %d", pid);
1350 }
1351 }
1352 return INVALID_NUB_PROCESS;
1353}
1354
1355// Do the process specific setup for attach. If this returns NULL, then there's no
1356// platform specific stuff to be done to wait for the attach. If you get non-null,
1357// pass that token to the CheckForProcess method, and then to CleanupAfterAttach.
1358
1359// Call PrepareForAttach before attaching to a process that has not yet launched
1360// This returns a token that can be passed to CheckForProcess, and to CleanupAfterAttach.
1361// You should call CleanupAfterAttach to free the token, and do whatever other
1362// cleanup seems good.
1363
1364const void *
1365MachProcess::PrepareForAttach (const char *path, nub_launch_flavor_t launch_flavor, bool waitfor, DNBError &err_str)
1366{
Jason Molenda42999a42012-02-22 02:18:59 +00001367#ifdef WITH_SPRINGBOARD
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001368 // Tell SpringBoard to halt the next launch of this application on startup.
1369
1370 if (!waitfor)
1371 return NULL;
1372
1373 const char *app_ext = strstr(path, ".app");
1374 if (app_ext == NULL)
1375 {
Greg Claytondce502e2011-11-04 03:34:56 +00001376 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::PrepareForAttach(): path '%s' doesn't contain .app, we can't tell springboard to wait for launch...", path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001377 return NULL;
1378 }
1379
1380 if (launch_flavor != eLaunchFlavorSpringBoard
1381 && launch_flavor != eLaunchFlavorDefault)
1382 return NULL;
1383
1384 std::string app_bundle_path(path, app_ext + strlen(".app"));
1385
1386 CFStringRef bundleIDCFStr = CopyBundleIDForPath (app_bundle_path.c_str (), err_str);
1387 std::string bundleIDStr;
1388 CFString::UTF8(bundleIDCFStr, bundleIDStr);
1389 DNBLogThreadedIf(LOG_PROCESS, "CopyBundleIDForPath (%s, err_str) returned @\"%s\"", app_bundle_path.c_str (), bundleIDStr.c_str());
1390
1391 if (bundleIDCFStr == NULL)
1392 {
1393 return NULL;
1394 }
1395
1396 SBSApplicationLaunchError sbs_error = 0;
1397
1398 const char *stdout_err = "/dev/null";
1399 CFString stdio_path;
1400 stdio_path.SetFileSystemRepresentation (stdout_err);
1401
1402 DNBLogThreadedIf(LOG_PROCESS, "SBSLaunchApplicationForDebugging ( @\"%s\" , NULL, NULL, NULL, @\"%s\", @\"%s\", SBSApplicationDebugOnNextLaunch | SBSApplicationLaunchWaitForDebugger )", bundleIDStr.c_str(), stdout_err, stdout_err);
1403 sbs_error = SBSLaunchApplicationForDebugging (bundleIDCFStr,
1404 (CFURLRef)NULL, // openURL
1405 NULL, // launch_argv.get(),
1406 NULL, // launch_envp.get(), // CFDictionaryRef environment
1407 stdio_path.get(),
1408 stdio_path.get(),
1409 SBSApplicationDebugOnNextLaunch | SBSApplicationLaunchWaitForDebugger);
1410
1411 if (sbs_error != SBSApplicationLaunchErrorSuccess)
1412 {
1413 err_str.SetError(sbs_error, DNBError::SpringBoard);
1414 return NULL;
1415 }
1416
1417 DNBLogThreadedIf(LOG_PROCESS, "Successfully set DebugOnNextLaunch.");
1418 return bundleIDCFStr;
1419# else
1420 return NULL;
1421#endif
1422}
1423
1424// Pass in the token you got from PrepareForAttach. If there is a process
1425// for that token, then the pid will be returned, otherwise INVALID_NUB_PROCESS
1426// will be returned.
1427
1428nub_process_t
1429MachProcess::CheckForProcess (const void *attach_token)
1430{
1431 if (attach_token == NULL)
1432 return INVALID_NUB_PROCESS;
1433
Jason Molenda42999a42012-02-22 02:18:59 +00001434#ifdef WITH_SPRINGBOARD
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001435 CFStringRef bundleIDCFStr = (CFStringRef) attach_token;
1436 Boolean got_it;
1437 nub_process_t attach_pid;
1438 got_it = SBSProcessIDForDisplayIdentifier(bundleIDCFStr, &attach_pid);
1439 if (got_it)
1440 return attach_pid;
1441 else
1442 return INVALID_NUB_PROCESS;
1443#endif
1444 return INVALID_NUB_PROCESS;
1445}
1446
1447// Call this to clean up after you have either attached or given up on the attach.
1448// Pass true for success if you have attached, false if you have not.
1449// The token will also be freed at this point, so you can't use it after calling
1450// this method.
1451
1452void
1453MachProcess::CleanupAfterAttach (const void *attach_token, bool success, DNBError &err_str)
1454{
Jason Molenda42999a42012-02-22 02:18:59 +00001455#ifdef WITH_SPRINGBOARD
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001456 if (attach_token == NULL)
1457 return;
1458
1459 // Tell SpringBoard to cancel the debug on next launch of this application
1460 // if we failed to attach
1461 if (!success)
1462 {
1463 SBSApplicationLaunchError sbs_error = 0;
1464 CFStringRef bundleIDCFStr = (CFStringRef) attach_token;
1465
1466 sbs_error = SBSLaunchApplicationForDebugging (bundleIDCFStr,
1467 (CFURLRef)NULL,
1468 NULL,
1469 NULL,
1470 NULL,
1471 NULL,
1472 SBSApplicationCancelDebugOnNextLaunch);
1473
1474 if (sbs_error != SBSApplicationLaunchErrorSuccess)
1475 {
1476 err_str.SetError(sbs_error, DNBError::SpringBoard);
1477 return;
1478 }
1479 }
1480
1481 CFRelease((CFStringRef) attach_token);
1482#endif
1483}
1484
1485pid_t
1486MachProcess::LaunchForDebug
1487(
1488 const char *path,
1489 char const *argv[],
1490 char const *envp[],
Greg Clayton6779606a2011-01-22 23:43:18 +00001491 const char *working_directory, // NULL => dont' change, non-NULL => set working directory for inferior to this
1492 const char *stdin_path,
1493 const char *stdout_path,
1494 const char *stderr_path,
Caroline Ticef8da8632010-12-03 18:46:09 +00001495 bool no_stdio,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001496 nub_launch_flavor_t launch_flavor,
Greg Claytonf681b942010-08-31 18:35:14 +00001497 int disable_aslr,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001498 DNBError &launch_err
1499)
1500{
1501 // Clear out and clean up from any current state
1502 Clear();
1503
Greg Claytonf681b942010-08-31 18:35:14 +00001504 DNBLogThreadedIf(LOG_PROCESS, "%s( path = '%s', argv = %p, envp = %p, launch_flavor = %u, disable_aslr = %d )", __FUNCTION__, path, argv, envp, launch_flavor, disable_aslr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001505
1506 // Fork a child process for debugging
1507 SetState(eStateLaunching);
1508
1509 switch (launch_flavor)
1510 {
1511 case eLaunchFlavorForkExec:
1512 m_pid = MachProcess::ForkChildForPTraceDebugging (path, argv, envp, this, launch_err);
1513 break;
1514
Johnny Chenbe4e2082012-06-11 21:05:26 +00001515#ifdef WITH_SPRINGBOARD
1516
1517 case eLaunchFlavorSpringBoard:
1518 {
1519 const char *app_ext = strstr(path, ".app");
1520 if (app_ext != NULL)
1521 {
1522 std::string app_bundle_path(path, app_ext + strlen(".app"));
1523 if (SBLaunchForDebug (app_bundle_path.c_str(), argv, envp, no_stdio, launch_err) != 0)
1524 return m_pid; // A successful SBLaunchForDebug() returns and assigns a non-zero m_pid.
1525 }
1526 }
1527 // In case the executable name has a ".app" fragment which confuses our debugserver,
1528 // let's do an intentional fallthrough here...
1529 launch_flavor = eLaunchFlavorPosixSpawn;
1530
1531#endif
1532
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001533 case eLaunchFlavorPosixSpawn:
Greg Clayton3af9ea52010-11-18 05:57:03 +00001534 m_pid = MachProcess::PosixSpawnChildForPTraceDebugging (path,
Greg Clayton3c144382010-12-01 22:45:40 +00001535 DNBArchProtocol::GetArchitecture (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001536 argv,
1537 envp,
Greg Clayton6779606a2011-01-22 23:43:18 +00001538 working_directory,
1539 stdin_path,
1540 stdout_path,
1541 stderr_path,
Caroline Ticef8da8632010-12-03 18:46:09 +00001542 no_stdio,
Greg Clayton3af9ea52010-11-18 05:57:03 +00001543 this,
1544 disable_aslr,
1545 launch_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001546 break;
1547
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001548 default:
1549 // Invalid launch
1550 launch_err.SetError(NUB_GENERIC_ERROR, DNBError::Generic);
1551 return INVALID_NUB_PROCESS;
1552 }
1553
1554 if (m_pid == INVALID_NUB_PROCESS)
1555 {
1556 // If we don't have a valid process ID and no one has set the error,
1557 // then return a generic error
1558 if (launch_err.Success())
1559 launch_err.SetError(NUB_GENERIC_ERROR, DNBError::Generic);
1560 }
1561 else
1562 {
1563 m_path = path;
1564 size_t i;
1565 char const *arg;
1566 for (i=0; (arg = argv[i]) != NULL; i++)
1567 m_args.push_back(arg);
1568
Greg Clayton3382c2c2010-07-30 23:14:42 +00001569 m_task.StartExceptionThread(launch_err);
1570 if (launch_err.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001571 {
Greg Clayton3382c2c2010-07-30 23:14:42 +00001572 if (launch_err.AsString() == NULL)
1573 launch_err.SetErrorString("unable to start the exception thread");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001574 ::ptrace (PT_KILL, m_pid, 0, 0);
1575 m_pid = INVALID_NUB_PROCESS;
1576 return INVALID_NUB_PROCESS;
1577 }
1578
1579 StartSTDIOThread();
1580
1581 if (launch_flavor == eLaunchFlavorPosixSpawn)
1582 {
1583
1584 SetState (eStateAttaching);
1585 errno = 0;
Caroline Tice5d7be2e2010-11-02 16:16:53 +00001586 int err = ::ptrace (PT_ATTACHEXC, m_pid, 0, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001587 if (err == 0)
1588 {
1589 m_flags |= eMachProcessFlagsAttached;
1590 DNBLogThreadedIf(LOG_PROCESS, "successfully spawned pid %d", m_pid);
1591 launch_err.Clear();
1592 }
1593 else
1594 {
1595 SetState (eStateExited);
1596 DNBError ptrace_err(errno, DNBError::POSIX);
1597 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());
1598 launch_err.SetError(NUB_GENERIC_ERROR, DNBError::Generic);
1599 }
1600 }
1601 else
1602 {
1603 launch_err.Clear();
1604 }
1605 }
1606 return m_pid;
1607}
1608
1609pid_t
1610MachProcess::PosixSpawnChildForPTraceDebugging
1611(
1612 const char *path,
Greg Clayton3af9ea52010-11-18 05:57:03 +00001613 cpu_type_t cpu_type,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001614 char const *argv[],
1615 char const *envp[],
Greg Clayton6779606a2011-01-22 23:43:18 +00001616 const char *working_directory,
1617 const char *stdin_path,
1618 const char *stdout_path,
1619 const char *stderr_path,
Caroline Ticef8da8632010-12-03 18:46:09 +00001620 bool no_stdio,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001621 MachProcess* process,
Greg Claytonf681b942010-08-31 18:35:14 +00001622 int disable_aslr,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001623 DNBError& err
1624)
1625{
1626 posix_spawnattr_t attr;
Greg Claytonf681b942010-08-31 18:35:14 +00001627 short flags;
Greg Claytonbd82a5d2011-01-23 05:56:20 +00001628 DNBLogThreadedIf(LOG_PROCESS, "%s ( path='%s', argv=%p, envp=%p, working_dir=%s, stdin=%s, stdout=%s stderr=%s, no-stdio=%i)",
1629 __FUNCTION__,
1630 path,
1631 argv,
1632 envp,
1633 working_directory,
1634 stdin_path,
1635 stdout_path,
1636 stderr_path,
1637 no_stdio);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001638
1639 err.SetError( ::posix_spawnattr_init (&attr), DNBError::POSIX);
1640 if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
1641 err.LogThreaded("::posix_spawnattr_init ( &attr )");
1642 if (err.Fail())
1643 return INVALID_NUB_PROCESS;
1644
Greg Clayton708c1ab2011-10-28 01:24:12 +00001645 flags = POSIX_SPAWN_START_SUSPENDED | POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
Greg Claytonf681b942010-08-31 18:35:14 +00001646 if (disable_aslr)
1647 flags |= _POSIX_SPAWN_DISABLE_ASLR;
Greg Clayton708c1ab2011-10-28 01:24:12 +00001648
1649 sigset_t no_signals;
1650 sigset_t all_signals;
1651 sigemptyset (&no_signals);
1652 sigfillset (&all_signals);
1653 ::posix_spawnattr_setsigmask(&attr, &no_signals);
1654 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
1655
Greg Claytonf681b942010-08-31 18:35:14 +00001656 err.SetError( ::posix_spawnattr_setflags (&attr, flags), DNBError::POSIX);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001657 if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
Greg Claytonf681b942010-08-31 18:35:14 +00001658 err.LogThreaded("::posix_spawnattr_setflags ( &attr, POSIX_SPAWN_START_SUSPENDED%s )", flags & _POSIX_SPAWN_DISABLE_ASLR ? " | _POSIX_SPAWN_DISABLE_ASLR" : "");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001659 if (err.Fail())
1660 return INVALID_NUB_PROCESS;
1661
1662 // Don't do this on SnowLeopard, _sometimes_ the TASK_BASIC_INFO will fail
1663 // and we will fail to continue with our process...
1664
1665 // On SnowLeopard we should set "DYLD_NO_PIE" in the inferior environment....
1666
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001667#if !defined(__arm__)
1668
1669 // We don't need to do this for ARM, and we really shouldn't now that we
1670 // have multiple CPU subtypes and no posix_spawnattr call that allows us
1671 // to set which CPU subtype to launch...
Greg Clayton71337622011-02-24 22:24:29 +00001672 if (cpu_type != 0)
1673 {
1674 size_t ocount = 0;
1675 err.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu_type, &ocount), DNBError::POSIX);
1676 if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
1677 err.LogThreaded("::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %zu )", cpu_type, ocount);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001678
Greg Clayton71337622011-02-24 22:24:29 +00001679 if (err.Fail() != 0 || ocount != 1)
1680 return INVALID_NUB_PROCESS;
1681 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001682#endif
1683
1684 PseudoTerminal pty;
1685
1686 posix_spawn_file_actions_t file_actions;
1687 err.SetError( ::posix_spawn_file_actions_init (&file_actions), DNBError::POSIX);
1688 int file_actions_valid = err.Success();
1689 if (!file_actions_valid || DNBLogCheckLogBit(LOG_PROCESS))
1690 err.LogThreaded("::posix_spawn_file_actions_init ( &file_actions )");
1691 int pty_error = -1;
1692 pid_t pid = INVALID_NUB_PROCESS;
1693 if (file_actions_valid)
1694 {
Greg Clayton6779606a2011-01-22 23:43:18 +00001695 if (stdin_path == NULL && stdout_path == NULL && stderr_path == NULL && !no_stdio)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001696 {
1697 pty_error = pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY);
1698 if (pty_error == PseudoTerminal::success)
Greg Clayton6779606a2011-01-22 23:43:18 +00001699 {
1700 stdin_path = stdout_path = stderr_path = pty.SlaveName();
1701 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001702 }
1703
Greg Clayton701a6b42012-03-12 19:02:41 +00001704 // if no_stdio or std paths not supplied, then route to "/dev/null".
1705 if (no_stdio || stdin_path == NULL || stdin_path[0] == '\0')
1706 stdin_path = "/dev/null";
1707 if (no_stdio || stdout_path == NULL || stdout_path[0] == '\0')
1708 stdout_path = "/dev/null";
1709 if (no_stdio || stderr_path == NULL || stderr_path[0] == '\0')
1710 stderr_path = "/dev/null";
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001711
Greg Clayton701a6b42012-03-12 19:02:41 +00001712 err.SetError( ::posix_spawn_file_actions_addopen (&file_actions,
1713 STDIN_FILENO,
1714 stdin_path,
1715 O_RDONLY | O_NOCTTY,
1716 0),
1717 DNBError::POSIX);
1718 if (err.Fail() || DNBLogCheckLogBit (LOG_PROCESS))
1719 err.LogThreaded ("::posix_spawn_file_actions_addopen (&file_actions, filedes=STDIN_FILENO, path='%s')", stdin_path);
1720
1721 err.SetError( ::posix_spawn_file_actions_addopen (&file_actions,
1722 STDOUT_FILENO,
1723 stdout_path,
1724 O_WRONLY | O_NOCTTY | O_CREAT,
1725 0640),
1726 DNBError::POSIX);
1727 if (err.Fail() || DNBLogCheckLogBit (LOG_PROCESS))
1728 err.LogThreaded ("::posix_spawn_file_actions_addopen (&file_actions, filedes=STDOUT_FILENO, path='%s')", stdout_path);
1729
1730 err.SetError( ::posix_spawn_file_actions_addopen (&file_actions,
1731 STDERR_FILENO,
1732 stderr_path,
1733 O_WRONLY | O_NOCTTY | O_CREAT,
1734 0640),
1735 DNBError::POSIX);
1736 if (err.Fail() || DNBLogCheckLogBit (LOG_PROCESS))
1737 err.LogThreaded ("::posix_spawn_file_actions_addopen (&file_actions, filedes=STDERR_FILENO, path='%s')", stderr_path);
Greg Claytonbd82a5d2011-01-23 05:56:20 +00001738
1739 // TODO: Verify if we can set the working directory back immediately
1740 // after the posix_spawnp call without creating a race condition???
1741 if (working_directory)
1742 ::chdir (working_directory);
1743
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001744 err.SetError( ::posix_spawnp (&pid, path, &file_actions, &attr, (char * const*)argv, (char * const*)envp), DNBError::POSIX);
1745 if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
1746 err.LogThreaded("::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )", pid, path, &file_actions, &attr, argv, envp);
1747 }
1748 else
1749 {
Greg Claytonbd82a5d2011-01-23 05:56:20 +00001750 // TODO: Verify if we can set the working directory back immediately
1751 // after the posix_spawnp call without creating a race condition???
1752 if (working_directory)
1753 ::chdir (working_directory);
1754
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001755 err.SetError( ::posix_spawnp (&pid, path, NULL, &attr, (char * const*)argv, (char * const*)envp), DNBError::POSIX);
1756 if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
1757 err.LogThreaded("::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )", pid, path, NULL, &attr, argv, envp);
1758 }
1759
1760 // We have seen some cases where posix_spawnp was returning a valid
1761 // looking pid even when an error was returned, so clear it out
1762 if (err.Fail())
1763 pid = INVALID_NUB_PROCESS;
1764
1765 if (pty_error == 0)
1766 {
1767 if (process != NULL)
1768 {
1769 int master_fd = pty.ReleaseMasterFD();
1770 process->SetChildFileDescriptors(master_fd, master_fd, master_fd);
1771 }
1772 }
Greg Clayton0b42ac32010-07-02 01:29:13 +00001773 ::posix_spawnattr_destroy (&attr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001774
Greg Clayton71337622011-02-24 22:24:29 +00001775 if (pid != INVALID_NUB_PROCESS)
1776 {
1777 cpu_type_t pid_cpu_type = MachProcess::GetCPUTypeForLocalProcess (pid);
1778 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( ) pid=%i, cpu_type=0x%8.8x", __FUNCTION__, pid, pid_cpu_type);
1779 if (pid_cpu_type)
1780 DNBArchProtocol::SetArchitecture (pid_cpu_type);
1781 }
1782
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001783 if (file_actions_valid)
1784 {
1785 DNBError err2;
1786 err2.SetError( ::posix_spawn_file_actions_destroy (&file_actions), DNBError::POSIX);
1787 if (err2.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
1788 err2.LogThreaded("::posix_spawn_file_actions_destroy ( &file_actions )");
1789 }
1790
1791 return pid;
1792}
1793
Greg Clayton71337622011-02-24 22:24:29 +00001794uint32_t
1795MachProcess::GetCPUTypeForLocalProcess (pid_t pid)
1796{
1797 int mib[CTL_MAXNAME]={0,};
1798 size_t len = CTL_MAXNAME;
1799 if (::sysctlnametomib("sysctl.proc_cputype", mib, &len))
1800 return 0;
1801
1802 mib[len] = pid;
1803 len++;
1804
1805 cpu_type_t cpu;
1806 size_t cpu_len = sizeof(cpu);
1807 if (::sysctl (mib, len, &cpu, &cpu_len, 0, 0))
1808 cpu = 0;
1809 return cpu;
1810}
1811
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001812pid_t
1813MachProcess::ForkChildForPTraceDebugging
1814(
1815 const char *path,
1816 char const *argv[],
1817 char const *envp[],
1818 MachProcess* process,
1819 DNBError& launch_err
1820)
1821{
1822 PseudoTerminal::Error pty_error = PseudoTerminal::success;
1823
1824 // Use a fork that ties the child process's stdin/out/err to a pseudo
1825 // terminal so we can read it in our MachProcess::STDIOThread
1826 // as unbuffered io.
1827 PseudoTerminal pty;
1828 pid_t pid = pty.Fork(pty_error);
1829
1830 if (pid < 0)
1831 {
1832 //--------------------------------------------------------------
1833 // Error during fork.
1834 //--------------------------------------------------------------
1835 return pid;
1836 }
1837 else if (pid == 0)
1838 {
1839 //--------------------------------------------------------------
1840 // Child process
1841 //--------------------------------------------------------------
1842 ::ptrace (PT_TRACE_ME, 0, 0, 0); // Debug this process
1843 ::ptrace (PT_SIGEXC, 0, 0, 0); // Get BSD signals as mach exceptions
1844
1845 // If our parent is setgid, lets make sure we don't inherit those
1846 // extra powers due to nepotism.
Greg Clayton23f59502012-07-17 03:23:13 +00001847 if (::setgid (getgid ()) == 0)
1848 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001849
Greg Clayton23f59502012-07-17 03:23:13 +00001850 // Let the child have its own process group. We need to execute
1851 // this call in both the child and parent to avoid a race condition
1852 // between the two processes.
1853 ::setpgid (0, 0); // Set the child process group to match its pid
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001854
Greg Clayton23f59502012-07-17 03:23:13 +00001855 // Sleep a bit to before the exec call
1856 ::sleep (1);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001857
Greg Clayton23f59502012-07-17 03:23:13 +00001858 // Turn this process into
1859 ::execv (path, (char * const *)argv);
1860 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001861 // Exit with error code. Child process should have taken
1862 // over in above exec call and if the exec fails it will
1863 // exit the child process below.
1864 ::exit (127);
1865 }
1866 else
1867 {
1868 //--------------------------------------------------------------
1869 // Parent process
1870 //--------------------------------------------------------------
1871 // Let the child have its own process group. We need to execute
1872 // this call in both the child and parent to avoid a race condition
1873 // between the two processes.
1874 ::setpgid (pid, pid); // Set the child process group to match its pid
1875
1876 if (process != NULL)
1877 {
1878 // Release our master pty file descriptor so the pty class doesn't
1879 // close it and so we can continue to use it in our STDIO thread
1880 int master_fd = pty.ReleaseMasterFD();
1881 process->SetChildFileDescriptors(master_fd, master_fd, master_fd);
1882 }
1883 }
1884 return pid;
1885}
1886
Jason Molenda42999a42012-02-22 02:18:59 +00001887#ifdef WITH_SPRINGBOARD
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001888
1889pid_t
Caroline Ticef8da8632010-12-03 18:46:09 +00001890MachProcess::SBLaunchForDebug (const char *path, char const *argv[], char const *envp[], bool no_stdio, DNBError &launch_err)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001891{
1892 // Clear out and clean up from any current state
1893 Clear();
1894
1895 DNBLogThreadedIf(LOG_PROCESS, "%s( '%s', argv)", __FUNCTION__, path);
1896
1897 // Fork a child process for debugging
1898 SetState(eStateLaunching);
Caroline Ticef8da8632010-12-03 18:46:09 +00001899 m_pid = MachProcess::SBForkChildForPTraceDebugging(path, argv, envp, no_stdio, this, launch_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001900 if (m_pid != 0)
1901 {
1902 m_flags |= eMachProcessFlagsUsingSBS;
1903 m_path = path;
1904 size_t i;
1905 char const *arg;
1906 for (i=0; (arg = argv[i]) != NULL; i++)
1907 m_args.push_back(arg);
Greg Clayton6f35f5c2010-09-09 06:32:46 +00001908 m_task.StartExceptionThread(launch_err);
1909
1910 if (launch_err.Fail())
1911 {
1912 if (launch_err.AsString() == NULL)
1913 launch_err.SetErrorString("unable to start the exception thread");
1914 ::ptrace (PT_KILL, m_pid, 0, 0);
1915 m_pid = INVALID_NUB_PROCESS;
1916 return INVALID_NUB_PROCESS;
1917 }
1918
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001919 StartSTDIOThread();
1920 SetState (eStateAttaching);
Caroline Tice5d7be2e2010-11-02 16:16:53 +00001921 int err = ::ptrace (PT_ATTACHEXC, m_pid, 0, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001922 if (err == 0)
1923 {
1924 m_flags |= eMachProcessFlagsAttached;
1925 DNBLogThreadedIf(LOG_PROCESS, "successfully attached to pid %d", m_pid);
1926 }
1927 else
1928 {
1929 SetState (eStateExited);
1930 DNBLogThreadedIf(LOG_PROCESS, "error: failed to attach to pid %d", m_pid);
1931 }
1932 }
1933 return m_pid;
1934}
1935
1936#include <servers/bootstrap.h>
1937
1938// This returns a CFRetained pointer to the Bundle ID for app_bundle_path,
1939// or NULL if there was some problem getting the bundle id.
1940static CFStringRef
1941CopyBundleIDForPath (const char *app_bundle_path, DNBError &err_str)
1942{
1943 CFBundle bundle(app_bundle_path);
1944 CFStringRef bundleIDCFStr = bundle.GetIdentifier();
1945 std::string bundleID;
1946 if (CFString::UTF8(bundleIDCFStr, bundleID) == NULL)
1947 {
1948 struct stat app_bundle_stat;
1949 char err_msg[PATH_MAX];
1950
1951 if (::stat (app_bundle_path, &app_bundle_stat) < 0)
1952 {
1953 err_str.SetError(errno, DNBError::POSIX);
1954 snprintf(err_msg, sizeof(err_msg), "%s: \"%s\"", err_str.AsString(), app_bundle_path);
1955 err_str.SetErrorString(err_msg);
1956 DNBLogThreadedIf(LOG_PROCESS, "%s() error: %s", __FUNCTION__, err_msg);
1957 }
1958 else
1959 {
1960 err_str.SetError(-1, DNBError::Generic);
1961 snprintf(err_msg, sizeof(err_msg), "failed to extract CFBundleIdentifier from %s", app_bundle_path);
1962 err_str.SetErrorString(err_msg);
1963 DNBLogThreadedIf(LOG_PROCESS, "%s() error: failed to extract CFBundleIdentifier from '%s'", __FUNCTION__, app_bundle_path);
1964 }
1965 return NULL;
1966 }
1967
1968 DNBLogThreadedIf(LOG_PROCESS, "%s() extracted CFBundleIdentifier: %s", __FUNCTION__, bundleID.c_str());
1969 CFRetain (bundleIDCFStr);
1970
1971 return bundleIDCFStr;
1972}
1973
1974pid_t
Caroline Ticef8da8632010-12-03 18:46:09 +00001975MachProcess::SBForkChildForPTraceDebugging (const char *app_bundle_path, char const *argv[], char const *envp[], bool no_stdio, MachProcess* process, DNBError &launch_err)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001976{
1977 DNBLogThreadedIf(LOG_PROCESS, "%s( '%s', argv, %p)", __FUNCTION__, app_bundle_path, process);
1978 CFAllocatorRef alloc = kCFAllocatorDefault;
1979
1980 if (argv[0] == NULL)
1981 return INVALID_NUB_PROCESS;
1982
1983 size_t argc = 0;
1984 // Count the number of arguments
1985 while (argv[argc] != NULL)
1986 argc++;
1987
1988 // Enumerate the arguments
1989 size_t first_launch_arg_idx = 1;
1990 CFReleaser<CFMutableArrayRef> launch_argv;
1991
1992 if (argv[first_launch_arg_idx])
1993 {
1994 size_t launch_argc = argc > 0 ? argc - 1 : 0;
1995 launch_argv.reset (::CFArrayCreateMutable (alloc, launch_argc, &kCFTypeArrayCallBacks));
1996 size_t i;
1997 char const *arg;
1998 CFString launch_arg;
1999 for (i=first_launch_arg_idx; (i < argc) && ((arg = argv[i]) != NULL); i++)
2000 {
2001 launch_arg.reset(::CFStringCreateWithCString (alloc, arg, kCFStringEncodingUTF8));
2002 if (launch_arg.get() != NULL)
2003 CFArrayAppendValue(launch_argv.get(), launch_arg.get());
2004 else
2005 break;
2006 }
2007 }
2008
2009 // Next fill in the arguments dictionary. Note, the envp array is of the form
2010 // Variable=value but SpringBoard wants a CF dictionary. So we have to convert
2011 // this here.
2012
2013 CFReleaser<CFMutableDictionaryRef> launch_envp;
2014
2015 if (envp[0])
2016 {
2017 launch_envp.reset(::CFDictionaryCreateMutable(alloc, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
2018 const char *value;
2019 int name_len;
2020 CFString name_string, value_string;
2021
2022 for (int i = 0; envp[i] != NULL; i++)
2023 {
2024 value = strstr (envp[i], "=");
2025
2026 // If the name field is empty or there's no =, skip it. Somebody's messing with us.
2027 if (value == NULL || value == envp[i])
2028 continue;
2029
2030 name_len = value - envp[i];
2031
2032 // Now move value over the "="
2033 value++;
2034
2035 name_string.reset(::CFStringCreateWithBytes(alloc, (const UInt8 *) envp[i], name_len, kCFStringEncodingUTF8, false));
2036 value_string.reset(::CFStringCreateWithCString(alloc, value, kCFStringEncodingUTF8));
2037 CFDictionarySetValue (launch_envp.get(), name_string.get(), value_string.get());
2038 }
2039 }
2040
2041 CFString stdio_path;
2042
2043 PseudoTerminal pty;
Caroline Ticef8da8632010-12-03 18:46:09 +00002044 if (!no_stdio)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002045 {
Caroline Ticef8da8632010-12-03 18:46:09 +00002046 PseudoTerminal::Error pty_err = pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY);
2047 if (pty_err == PseudoTerminal::success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002048 {
Caroline Ticef8da8632010-12-03 18:46:09 +00002049 const char* slave_name = pty.SlaveName();
2050 DNBLogThreadedIf(LOG_PROCESS, "%s() successfully opened master pty, slave is %s", __FUNCTION__, slave_name);
2051 if (slave_name && slave_name[0])
2052 {
2053 ::chmod (slave_name, S_IRWXU | S_IRWXG | S_IRWXO);
2054 stdio_path.SetFileSystemRepresentation (slave_name);
2055 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002056 }
2057 }
Caroline Ticef8da8632010-12-03 18:46:09 +00002058
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002059 if (stdio_path.get() == NULL)
2060 {
2061 stdio_path.SetFileSystemRepresentation ("/dev/null");
2062 }
2063
2064 CFStringRef bundleIDCFStr = CopyBundleIDForPath (app_bundle_path, launch_err);
2065 if (bundleIDCFStr == NULL)
2066 return INVALID_NUB_PROCESS;
2067
2068 std::string bundleID;
2069 CFString::UTF8(bundleIDCFStr, bundleID);
2070
2071 CFData argv_data(NULL);
2072
2073 if (launch_argv.get())
2074 {
2075 if (argv_data.Serialize(launch_argv.get(), kCFPropertyListBinaryFormat_v1_0) == NULL)
2076 {
2077 DNBLogThreadedIf(LOG_PROCESS, "%s() error: failed to serialize launch arg array...", __FUNCTION__);
2078 return INVALID_NUB_PROCESS;
2079 }
2080 }
2081
2082 DNBLogThreadedIf(LOG_PROCESS, "%s() serialized launch arg array", __FUNCTION__);
2083
2084 // Find SpringBoard
2085 SBSApplicationLaunchError sbs_error = 0;
2086 sbs_error = SBSLaunchApplicationForDebugging (bundleIDCFStr,
2087 (CFURLRef)NULL, // openURL
2088 launch_argv.get(),
2089 launch_envp.get(), // CFDictionaryRef environment
2090 stdio_path.get(),
2091 stdio_path.get(),
2092 SBSApplicationLaunchWaitForDebugger | SBSApplicationLaunchUnlockDevice);
2093
2094
2095 launch_err.SetError(sbs_error, DNBError::SpringBoard);
2096
2097 if (sbs_error == SBSApplicationLaunchErrorSuccess)
2098 {
2099 static const useconds_t pid_poll_interval = 200000;
2100 static const useconds_t pid_poll_timeout = 30000000;
2101
2102 useconds_t pid_poll_total = 0;
2103
2104 nub_process_t pid = INVALID_NUB_PROCESS;
2105 Boolean pid_found = SBSProcessIDForDisplayIdentifier(bundleIDCFStr, &pid);
2106 // Poll until the process is running, as long as we are getting valid responses and the timeout hasn't expired
2107 // A return PID of 0 means the process is not running, which may be because it hasn't been (asynchronously) started
2108 // yet, or that it died very quickly (if you weren't using waitForDebugger).
2109 while (!pid_found && pid_poll_total < pid_poll_timeout)
2110 {
2111 usleep (pid_poll_interval);
2112 pid_poll_total += pid_poll_interval;
2113 DNBLogThreadedIf(LOG_PROCESS, "%s() polling Springboard for pid for %s...", __FUNCTION__, bundleID.c_str());
2114 pid_found = SBSProcessIDForDisplayIdentifier(bundleIDCFStr, &pid);
2115 }
2116
2117 CFRelease (bundleIDCFStr);
2118 if (pid_found)
2119 {
2120 if (process != NULL)
2121 {
2122 // Release our master pty file descriptor so the pty class doesn't
2123 // close it and so we can continue to use it in our STDIO thread
2124 int master_fd = pty.ReleaseMasterFD();
2125 process->SetChildFileDescriptors(master_fd, master_fd, master_fd);
2126 }
2127 DNBLogThreadedIf(LOG_PROCESS, "%s() => pid = %4.4x", __FUNCTION__, pid);
2128 }
2129 else
2130 {
2131 DNBLogError("failed to lookup the process ID for CFBundleIdentifier %s.", bundleID.c_str());
2132 }
2133 return pid;
2134 }
2135
2136 DNBLogError("unable to launch the application with CFBundleIdentifier '%s' sbs_error = %u", bundleID.c_str(), sbs_error);
2137 return INVALID_NUB_PROCESS;
2138}
2139
Jason Molenda42999a42012-02-22 02:18:59 +00002140#endif // #ifdef WITH_SPRINGBOARD
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002141
2142