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