1 //===-- debugserver.cpp -----------------------------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include <arpa/inet.h> 10 #include <asl.h> 11 #include <crt_externs.h> 12 #include <errno.h> 13 #include <getopt.h> 14 #include <netdb.h> 15 #include <netinet/in.h> 16 #include <netinet/tcp.h> 17 #include <string> 18 #include <sys/select.h> 19 #include <sys/socket.h> 20 #include <sys/sysctl.h> 21 #include <sys/types.h> 22 #include <sys/un.h> 23 24 #include <memory> 25 #include <vector> 26 27 #if defined(__APPLE__) 28 #include <sched.h> 29 extern "C" int proc_set_wakemon_params(pid_t, int, 30 int); // <libproc_internal.h> SPI 31 #endif 32 33 #include "CFString.h" 34 #include "DNB.h" 35 #include "DNBLog.h" 36 #include "DNBTimer.h" 37 #include "OsLogger.h" 38 #include "PseudoTerminal.h" 39 #include "RNBContext.h" 40 #include "RNBRemote.h" 41 #include "RNBServices.h" 42 #include "RNBSocket.h" 43 #include "SysSignal.h" 44 45 // Global PID in case we get a signal and need to stop the process... 46 nub_process_t g_pid = INVALID_NUB_PROCESS; 47 48 // Run loop modes which determine which run loop function will be called 49 enum RNBRunLoopMode { 50 eRNBRunLoopModeInvalid = 0, 51 eRNBRunLoopModeGetStartModeFromRemoteProtocol, 52 eRNBRunLoopModeInferiorAttaching, 53 eRNBRunLoopModeInferiorLaunching, 54 eRNBRunLoopModeInferiorExecuting, 55 eRNBRunLoopModePlatformMode, 56 eRNBRunLoopModeExit 57 }; 58 59 // Global Variables 60 RNBRemoteSP g_remoteSP; 61 static int g_lockdown_opt = 0; 62 static int g_applist_opt = 0; 63 static nub_launch_flavor_t g_launch_flavor = eLaunchFlavorDefault; 64 int g_disable_aslr = 0; 65 66 int g_isatty = 0; 67 bool g_detach_on_error = true; 68 69 #define RNBLogSTDOUT(fmt, ...) \ 70 do { \ 71 if (g_isatty) { \ 72 fprintf(stdout, fmt, ##__VA_ARGS__); \ 73 } else { \ 74 _DNBLog(0, fmt, ##__VA_ARGS__); \ 75 } \ 76 } while (0) 77 #define RNBLogSTDERR(fmt, ...) \ 78 do { \ 79 if (g_isatty) { \ 80 fprintf(stderr, fmt, ##__VA_ARGS__); \ 81 } else { \ 82 _DNBLog(0, fmt, ##__VA_ARGS__); \ 83 } \ 84 } while (0) 85 86 // Get our program path and arguments from the remote connection. 87 // We will need to start up the remote connection without a PID, get the 88 // arguments, wait for the new process to finish launching and hit its 89 // entry point, and then return the run loop mode that should come next. 90 RNBRunLoopMode RNBRunLoopGetStartModeFromRemote(RNBRemote *remote) { 91 std::string packet; 92 93 if (remote) { 94 RNBContext &ctx = remote->Context(); 95 uint32_t event_mask = RNBContext::event_read_packet_available | 96 RNBContext::event_read_thread_exiting; 97 98 // Spin waiting to get the A packet. 99 while (true) { 100 DNBLogThreadedIf(LOG_RNB_MAX, 101 "%s ctx.Events().WaitForSetEvents( 0x%08x ) ...", 102 __FUNCTION__, event_mask); 103 nub_event_t set_events = ctx.Events().WaitForSetEvents(event_mask); 104 DNBLogThreadedIf(LOG_RNB_MAX, 105 "%s ctx.Events().WaitForSetEvents( 0x%08x ) => 0x%08x", 106 __FUNCTION__, event_mask, set_events); 107 108 if (set_events & RNBContext::event_read_thread_exiting) { 109 RNBLogSTDERR("error: packet read thread exited.\n"); 110 return eRNBRunLoopModeExit; 111 } 112 113 if (set_events & RNBContext::event_read_packet_available) { 114 rnb_err_t err = rnb_err; 115 RNBRemote::PacketEnum type; 116 117 err = remote->HandleReceivedPacket(&type); 118 119 // check if we tried to attach to a process 120 if (type == RNBRemote::vattach || type == RNBRemote::vattachwait || 121 type == RNBRemote::vattachorwait) { 122 if (err == rnb_success) { 123 RNBLogSTDOUT("Attach succeeded, ready to debug.\n"); 124 return eRNBRunLoopModeInferiorExecuting; 125 } else { 126 RNBLogSTDERR("error: attach failed.\n"); 127 return eRNBRunLoopModeExit; 128 } 129 } 130 131 if (err == rnb_success) { 132 // If we got our arguments we are ready to launch using the arguments 133 // and any environment variables we received. 134 if (type == RNBRemote::set_argv) { 135 return eRNBRunLoopModeInferiorLaunching; 136 } 137 } else if (err == rnb_not_connected) { 138 RNBLogSTDERR("error: connection lost.\n"); 139 return eRNBRunLoopModeExit; 140 } else { 141 // a catch all for any other gdb remote packets that failed 142 DNBLogThreadedIf(LOG_RNB_MINIMAL, "%s Error getting packet.", 143 __FUNCTION__); 144 continue; 145 } 146 147 DNBLogThreadedIf(LOG_RNB_MINIMAL, "#### %s", __FUNCTION__); 148 } else { 149 DNBLogThreadedIf(LOG_RNB_MINIMAL, 150 "%s Connection closed before getting \"A\" packet.", 151 __FUNCTION__); 152 return eRNBRunLoopModeExit; 153 } 154 } 155 } 156 return eRNBRunLoopModeExit; 157 } 158 159 // This run loop mode will wait for the process to launch and hit its 160 // entry point. It will currently ignore all events except for the 161 // process state changed event, where it watches for the process stopped 162 // or crash process state. 163 RNBRunLoopMode RNBRunLoopLaunchInferior(RNBRemote *remote, 164 const char *stdin_path, 165 const char *stdout_path, 166 const char *stderr_path, 167 bool no_stdio) { 168 RNBContext &ctx = remote->Context(); 169 170 // The Process stuff takes a c array, the RNBContext has a vector... 171 // So make up a c array. 172 173 DNBLogThreadedIf(LOG_RNB_MINIMAL, "%s Launching '%s'...", __FUNCTION__, 174 ctx.ArgumentAtIndex(0)); 175 176 size_t inferior_argc = ctx.ArgumentCount(); 177 // Initialize inferior_argv with inferior_argc + 1 NULLs 178 std::vector<const char *> inferior_argv(inferior_argc + 1, NULL); 179 180 size_t i; 181 for (i = 0; i < inferior_argc; i++) 182 inferior_argv[i] = ctx.ArgumentAtIndex(i); 183 184 // Pass the environment array the same way: 185 186 size_t inferior_envc = ctx.EnvironmentCount(); 187 // Initialize inferior_argv with inferior_argc + 1 NULLs 188 std::vector<const char *> inferior_envp(inferior_envc + 1, NULL); 189 190 for (i = 0; i < inferior_envc; i++) 191 inferior_envp[i] = ctx.EnvironmentAtIndex(i); 192 193 // Our launch type hasn't been set to anything concrete, so we need to 194 // figure our how we are going to launch automatically. 195 196 nub_launch_flavor_t launch_flavor = g_launch_flavor; 197 if (launch_flavor == eLaunchFlavorDefault) { 198 // Our default launch method is posix spawn 199 launch_flavor = eLaunchFlavorPosixSpawn; 200 201 #if defined WITH_FBS 202 // Check if we have an app bundle, if so launch using BackBoard Services. 203 if (strstr(inferior_argv[0], ".app")) { 204 launch_flavor = eLaunchFlavorFBS; 205 } 206 #elif defined WITH_BKS 207 // Check if we have an app bundle, if so launch using BackBoard Services. 208 if (strstr(inferior_argv[0], ".app")) { 209 launch_flavor = eLaunchFlavorBKS; 210 } 211 #elif defined WITH_SPRINGBOARD 212 // Check if we have an app bundle, if so launch using SpringBoard. 213 if (strstr(inferior_argv[0], ".app")) { 214 launch_flavor = eLaunchFlavorSpringBoard; 215 } 216 #endif 217 } 218 219 ctx.SetLaunchFlavor(launch_flavor); 220 char resolved_path[PATH_MAX]; 221 222 // If we fail to resolve the path to our executable, then just use what we 223 // were given and hope for the best 224 if (!DNBResolveExecutablePath(inferior_argv[0], resolved_path, 225 sizeof(resolved_path))) 226 ::strlcpy(resolved_path, inferior_argv[0], sizeof(resolved_path)); 227 228 char launch_err_str[PATH_MAX]; 229 launch_err_str[0] = '\0'; 230 const char *cwd = 231 (ctx.GetWorkingDirPath() != NULL ? ctx.GetWorkingDirPath() 232 : ctx.GetWorkingDirectory()); 233 const char *process_event = ctx.GetProcessEvent(); 234 nub_process_t pid = DNBProcessLaunch( 235 resolved_path, &inferior_argv[0], &inferior_envp[0], cwd, stdin_path, 236 stdout_path, stderr_path, no_stdio, launch_flavor, g_disable_aslr, 237 process_event, launch_err_str, sizeof(launch_err_str)); 238 239 g_pid = pid; 240 241 if (pid == INVALID_NUB_PROCESS && strlen(launch_err_str) > 0) { 242 DNBLogThreaded("%s DNBProcessLaunch() returned error: '%s'", __FUNCTION__, 243 launch_err_str); 244 ctx.LaunchStatus().SetError(-1, DNBError::Generic); 245 ctx.LaunchStatus().SetErrorString(launch_err_str); 246 } else if (pid == INVALID_NUB_PROCESS) { 247 DNBLogThreaded( 248 "%s DNBProcessLaunch() failed to launch process, unknown failure", 249 __FUNCTION__); 250 ctx.LaunchStatus().SetError(-1, DNBError::Generic); 251 ctx.LaunchStatus().SetErrorString("<unknown failure>"); 252 } else { 253 ctx.LaunchStatus().Clear(); 254 } 255 256 if (remote->Comm().IsConnected()) { 257 // It we are connected already, the next thing gdb will do is ask 258 // whether the launch succeeded, and if not, whether there is an 259 // error code. So we need to fetch one packet from gdb before we wait 260 // on the stop from the target. 261 262 uint32_t event_mask = RNBContext::event_read_packet_available; 263 nub_event_t set_events = ctx.Events().WaitForSetEvents(event_mask); 264 265 if (set_events & RNBContext::event_read_packet_available) { 266 rnb_err_t err = rnb_err; 267 RNBRemote::PacketEnum type; 268 269 err = remote->HandleReceivedPacket(&type); 270 271 if (err != rnb_success) { 272 DNBLogThreadedIf(LOG_RNB_MINIMAL, "%s Error getting packet.", 273 __FUNCTION__); 274 return eRNBRunLoopModeExit; 275 } 276 if (type != RNBRemote::query_launch_success) { 277 DNBLogThreadedIf(LOG_RNB_MINIMAL, 278 "%s Didn't get the expected qLaunchSuccess packet.", 279 __FUNCTION__); 280 } 281 } 282 } 283 284 while (pid != INVALID_NUB_PROCESS) { 285 // Wait for process to start up and hit entry point 286 DNBLogThreadedIf(LOG_RNB_EVENTS, "%s DNBProcessWaitForEvent (%4.4x, " 287 "eEventProcessRunningStateChanged | " 288 "eEventProcessStoppedStateChanged, true, " 289 "INFINITE)...", 290 __FUNCTION__, pid); 291 nub_event_t set_events = 292 DNBProcessWaitForEvents(pid, eEventProcessRunningStateChanged | 293 eEventProcessStoppedStateChanged, 294 true, NULL); 295 DNBLogThreadedIf(LOG_RNB_EVENTS, "%s DNBProcessWaitForEvent (%4.4x, " 296 "eEventProcessRunningStateChanged | " 297 "eEventProcessStoppedStateChanged, true, " 298 "INFINITE) => 0x%8.8x", 299 __FUNCTION__, pid, set_events); 300 301 if (set_events == 0) { 302 pid = INVALID_NUB_PROCESS; 303 g_pid = pid; 304 } else { 305 if (set_events & (eEventProcessRunningStateChanged | 306 eEventProcessStoppedStateChanged)) { 307 nub_state_t pid_state = DNBProcessGetState(pid); 308 DNBLogThreadedIf( 309 LOG_RNB_EVENTS, 310 "%s process %4.4x state changed (eEventProcessStateChanged): %s", 311 __FUNCTION__, pid, DNBStateAsString(pid_state)); 312 313 switch (pid_state) { 314 case eStateInvalid: 315 case eStateUnloaded: 316 case eStateAttaching: 317 case eStateLaunching: 318 case eStateSuspended: 319 break; // Ignore 320 321 case eStateRunning: 322 case eStateStepping: 323 // Still waiting to stop at entry point... 324 break; 325 326 case eStateStopped: 327 case eStateCrashed: 328 ctx.SetProcessID(pid); 329 return eRNBRunLoopModeInferiorExecuting; 330 331 case eStateDetached: 332 case eStateExited: 333 pid = INVALID_NUB_PROCESS; 334 g_pid = pid; 335 return eRNBRunLoopModeExit; 336 } 337 } 338 339 DNBProcessResetEvents(pid, set_events); 340 } 341 } 342 343 return eRNBRunLoopModeExit; 344 } 345 346 // This run loop mode will wait for the process to launch and hit its 347 // entry point. It will currently ignore all events except for the 348 // process state changed event, where it watches for the process stopped 349 // or crash process state. 350 RNBRunLoopMode RNBRunLoopLaunchAttaching(RNBRemote *remote, 351 nub_process_t attach_pid, 352 nub_process_t &pid) { 353 RNBContext &ctx = remote->Context(); 354 355 DNBLogThreadedIf(LOG_RNB_MINIMAL, "%s Attaching to pid %i...", __FUNCTION__, 356 attach_pid); 357 char err_str[1024]; 358 pid = DNBProcessAttach(attach_pid, NULL, err_str, sizeof(err_str)); 359 g_pid = pid; 360 361 if (pid == INVALID_NUB_PROCESS) { 362 ctx.LaunchStatus().SetError(-1, DNBError::Generic); 363 if (err_str[0]) 364 ctx.LaunchStatus().SetErrorString(err_str); 365 return eRNBRunLoopModeExit; 366 } else { 367 ctx.SetProcessID(pid); 368 return eRNBRunLoopModeInferiorExecuting; 369 } 370 } 371 372 // Watch for signals: 373 // SIGINT: so we can halt our inferior. (disabled for now) 374 // SIGPIPE: in case our child process dies 375 int g_sigint_received = 0; 376 int g_sigpipe_received = 0; 377 void signal_handler(int signo) { 378 DNBLogThreadedIf(LOG_RNB_MINIMAL, "%s (%s)", __FUNCTION__, 379 SysSignal::Name(signo)); 380 381 switch (signo) { 382 case SIGINT: 383 g_sigint_received++; 384 if (g_pid != INVALID_NUB_PROCESS) { 385 // Only send a SIGINT once... 386 if (g_sigint_received == 1) { 387 switch (DNBProcessGetState(g_pid)) { 388 case eStateRunning: 389 case eStateStepping: 390 DNBProcessSignal(g_pid, SIGSTOP); 391 return; 392 default: 393 break; 394 } 395 } 396 } 397 exit(SIGINT); 398 break; 399 400 case SIGPIPE: 401 g_sigpipe_received = 1; 402 break; 403 } 404 } 405 406 // Return the new run loop mode based off of the current process state 407 RNBRunLoopMode HandleProcessStateChange(RNBRemote *remote, bool initialize) { 408 RNBContext &ctx = remote->Context(); 409 nub_process_t pid = ctx.ProcessID(); 410 411 if (pid == INVALID_NUB_PROCESS) { 412 DNBLogThreadedIf(LOG_RNB_MINIMAL, "#### %s error: pid invalid, exiting...", 413 __FUNCTION__); 414 return eRNBRunLoopModeExit; 415 } 416 nub_state_t pid_state = DNBProcessGetState(pid); 417 418 DNBLogThreadedIf(LOG_RNB_MINIMAL, 419 "%s (&remote, initialize=%i) pid_state = %s", __FUNCTION__, 420 (int)initialize, DNBStateAsString(pid_state)); 421 422 switch (pid_state) { 423 case eStateInvalid: 424 case eStateUnloaded: 425 // Something bad happened 426 return eRNBRunLoopModeExit; 427 break; 428 429 case eStateAttaching: 430 case eStateLaunching: 431 return eRNBRunLoopModeInferiorExecuting; 432 433 case eStateSuspended: 434 case eStateCrashed: 435 case eStateStopped: 436 // If we stop due to a signal, so clear the fact that we got a SIGINT 437 // so we can stop ourselves again (but only while our inferior 438 // process is running..) 439 g_sigint_received = 0; 440 if (initialize == false) { 441 // Compare the last stop count to our current notion of a stop count 442 // to make sure we don't notify more than once for a given stop. 443 nub_size_t prev_pid_stop_count = ctx.GetProcessStopCount(); 444 bool pid_stop_count_changed = 445 ctx.SetProcessStopCount(DNBProcessGetStopCount(pid)); 446 if (pid_stop_count_changed) { 447 remote->FlushSTDIO(); 448 449 if (ctx.GetProcessStopCount() == 1) { 450 DNBLogThreadedIf( 451 LOG_RNB_MINIMAL, "%s (&remote, initialize=%i) pid_state = %s " 452 "pid_stop_count %llu (old %llu)) Notify??? no, " 453 "first stop...", 454 __FUNCTION__, (int)initialize, DNBStateAsString(pid_state), 455 (uint64_t)ctx.GetProcessStopCount(), 456 (uint64_t)prev_pid_stop_count); 457 } else { 458 459 DNBLogThreadedIf(LOG_RNB_MINIMAL, "%s (&remote, initialize=%i) " 460 "pid_state = %s pid_stop_count " 461 "%llu (old %llu)) Notify??? YES!!!", 462 __FUNCTION__, (int)initialize, 463 DNBStateAsString(pid_state), 464 (uint64_t)ctx.GetProcessStopCount(), 465 (uint64_t)prev_pid_stop_count); 466 remote->NotifyThatProcessStopped(); 467 } 468 } else { 469 DNBLogThreadedIf( 470 LOG_RNB_MINIMAL, "%s (&remote, initialize=%i) pid_state = %s " 471 "pid_stop_count %llu (old %llu)) Notify??? " 472 "skipping...", 473 __FUNCTION__, (int)initialize, DNBStateAsString(pid_state), 474 (uint64_t)ctx.GetProcessStopCount(), (uint64_t)prev_pid_stop_count); 475 } 476 } 477 return eRNBRunLoopModeInferiorExecuting; 478 479 case eStateStepping: 480 case eStateRunning: 481 return eRNBRunLoopModeInferiorExecuting; 482 483 case eStateExited: 484 remote->HandlePacket_last_signal(NULL); 485 return eRNBRunLoopModeExit; 486 case eStateDetached: 487 return eRNBRunLoopModeExit; 488 } 489 490 // Catch all... 491 return eRNBRunLoopModeExit; 492 } 493 494 // This function handles the case where our inferior program is stopped and 495 // we are waiting for gdb remote protocol packets. When a packet occurs that 496 // makes the inferior run, we need to leave this function with a new state 497 // as the return code. 498 RNBRunLoopMode RNBRunLoopInferiorExecuting(RNBRemote *remote) { 499 DNBLogThreadedIf(LOG_RNB_MINIMAL, "#### %s", __FUNCTION__); 500 RNBContext &ctx = remote->Context(); 501 502 // Init our mode and set 'is_running' based on the current process state 503 RNBRunLoopMode mode = HandleProcessStateChange(remote, true); 504 505 while (ctx.ProcessID() != INVALID_NUB_PROCESS) { 506 507 std::string set_events_str; 508 uint32_t event_mask = ctx.NormalEventBits(); 509 510 if (!ctx.ProcessStateRunning()) { 511 // Clear some bits if we are not running so we don't send any async 512 // packets 513 event_mask &= ~RNBContext::event_proc_stdio_available; 514 event_mask &= ~RNBContext::event_proc_profile_data; 515 // When we enable async structured data packets over another logical 516 // channel, 517 // this can be relaxed. 518 event_mask &= ~RNBContext::event_darwin_log_data_available; 519 } 520 521 // We want to make sure we consume all process state changes and have 522 // whomever is notifying us to wait for us to reset the event bit before 523 // continuing. 524 // ctx.Events().SetResetAckMask (RNBContext::event_proc_state_changed); 525 526 DNBLogThreadedIf(LOG_RNB_EVENTS, 527 "%s ctx.Events().WaitForSetEvents(0x%08x) ...", 528 __FUNCTION__, event_mask); 529 nub_event_t set_events = ctx.Events().WaitForSetEvents(event_mask); 530 DNBLogThreadedIf(LOG_RNB_EVENTS, 531 "%s ctx.Events().WaitForSetEvents(0x%08x) => 0x%08x (%s)", 532 __FUNCTION__, event_mask, set_events, 533 ctx.EventsAsString(set_events, set_events_str)); 534 535 if (set_events) { 536 if ((set_events & RNBContext::event_proc_thread_exiting) || 537 (set_events & RNBContext::event_proc_stdio_available)) { 538 remote->FlushSTDIO(); 539 } 540 541 if (set_events & RNBContext::event_proc_profile_data) { 542 remote->SendAsyncProfileData(); 543 } 544 545 if (set_events & RNBContext::event_darwin_log_data_available) { 546 remote->SendAsyncDarwinLogData(); 547 } 548 549 if (set_events & RNBContext::event_read_packet_available) { 550 // handleReceivedPacket will take care of resetting the 551 // event_read_packet_available events when there are no more... 552 set_events ^= RNBContext::event_read_packet_available; 553 554 if (ctx.ProcessStateRunning()) { 555 if (remote->HandleAsyncPacket() == rnb_not_connected) { 556 // TODO: connect again? Exit? 557 } 558 } else { 559 if (remote->HandleReceivedPacket() == rnb_not_connected) { 560 // TODO: connect again? Exit? 561 } 562 } 563 } 564 565 if (set_events & RNBContext::event_proc_state_changed) { 566 mode = HandleProcessStateChange(remote, false); 567 ctx.Events().ResetEvents(RNBContext::event_proc_state_changed); 568 set_events ^= RNBContext::event_proc_state_changed; 569 } 570 571 if (set_events & RNBContext::event_proc_thread_exiting) { 572 mode = eRNBRunLoopModeExit; 573 } 574 575 if (set_events & RNBContext::event_read_thread_exiting) { 576 // Out remote packet receiving thread exited, exit for now. 577 if (ctx.HasValidProcessID()) { 578 // TODO: We should add code that will leave the current process 579 // in its current state and listen for another connection... 580 if (ctx.ProcessStateRunning()) { 581 if (ctx.GetDetachOnError()) { 582 DNBLog("debugserver's event read thread is exiting, detaching " 583 "from the inferior process."); 584 DNBProcessDetach(ctx.ProcessID()); 585 } else { 586 DNBLog("debugserver's event read thread is exiting, killing the " 587 "inferior process."); 588 DNBProcessKill(ctx.ProcessID()); 589 } 590 } else { 591 if (ctx.GetDetachOnError()) { 592 DNBLog("debugserver's event read thread is exiting, detaching " 593 "from the inferior process."); 594 DNBProcessDetach(ctx.ProcessID()); 595 } 596 } 597 } 598 mode = eRNBRunLoopModeExit; 599 } 600 } 601 602 // Reset all event bits that weren't reset for now... 603 if (set_events != 0) 604 ctx.Events().ResetEvents(set_events); 605 606 if (mode != eRNBRunLoopModeInferiorExecuting) 607 break; 608 } 609 610 return mode; 611 } 612 613 RNBRunLoopMode RNBRunLoopPlatform(RNBRemote *remote) { 614 RNBRunLoopMode mode = eRNBRunLoopModePlatformMode; 615 RNBContext &ctx = remote->Context(); 616 617 while (mode == eRNBRunLoopModePlatformMode) { 618 std::string set_events_str; 619 const uint32_t event_mask = RNBContext::event_read_packet_available | 620 RNBContext::event_read_thread_exiting; 621 622 DNBLogThreadedIf(LOG_RNB_EVENTS, 623 "%s ctx.Events().WaitForSetEvents(0x%08x) ...", 624 __FUNCTION__, event_mask); 625 nub_event_t set_events = ctx.Events().WaitForSetEvents(event_mask); 626 DNBLogThreadedIf(LOG_RNB_EVENTS, 627 "%s ctx.Events().WaitForSetEvents(0x%08x) => 0x%08x (%s)", 628 __FUNCTION__, event_mask, set_events, 629 ctx.EventsAsString(set_events, set_events_str)); 630 631 if (set_events) { 632 if (set_events & RNBContext::event_read_packet_available) { 633 if (remote->HandleReceivedPacket() == rnb_not_connected) 634 mode = eRNBRunLoopModeExit; 635 } 636 637 if (set_events & RNBContext::event_read_thread_exiting) { 638 mode = eRNBRunLoopModeExit; 639 } 640 ctx.Events().ResetEvents(set_events); 641 } 642 } 643 return eRNBRunLoopModeExit; 644 } 645 646 // Convenience function to set up the remote listening port 647 // Returns 1 for success 0 for failure. 648 649 static void PortWasBoundCallbackUnixSocket(const void *baton, in_port_t port) { 650 //::printf ("PortWasBoundCallbackUnixSocket (baton = %p, port = %u)\n", baton, 651 //port); 652 653 const char *unix_socket_name = (const char *)baton; 654 655 if (unix_socket_name && unix_socket_name[0]) { 656 // We were given a unix socket name to use to communicate the port 657 // that we ended up binding to back to our parent process 658 struct sockaddr_un saddr_un; 659 int s = ::socket(AF_UNIX, SOCK_STREAM, 0); 660 if (s < 0) { 661 perror("error: socket (AF_UNIX, SOCK_STREAM, 0)"); 662 exit(1); 663 } 664 665 saddr_un.sun_family = AF_UNIX; 666 ::strlcpy(saddr_un.sun_path, unix_socket_name, 667 sizeof(saddr_un.sun_path) - 1); 668 saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0'; 669 saddr_un.sun_len = SUN_LEN(&saddr_un); 670 671 if (::connect(s, (struct sockaddr *)&saddr_un, 672 static_cast<socklen_t>(SUN_LEN(&saddr_un))) < 0) { 673 perror("error: connect (socket, &saddr_un, saddr_un_len)"); 674 exit(1); 675 } 676 677 //::printf ("connect () sucess!!\n"); 678 679 // We were able to connect to the socket, now write our PID so whomever 680 // launched us will know this process's ID 681 RNBLogSTDOUT("Listening to port %i...\n", port); 682 683 char pid_str[64]; 684 const int pid_str_len = ::snprintf(pid_str, sizeof(pid_str), "%u", port); 685 const ssize_t bytes_sent = ::send(s, pid_str, pid_str_len, 0); 686 687 if (pid_str_len != bytes_sent) { 688 perror("error: send (s, pid_str, pid_str_len, 0)"); 689 exit(1); 690 } 691 692 //::printf ("send () sucess!!\n"); 693 694 // We are done with the socket 695 close(s); 696 } 697 } 698 699 static void PortWasBoundCallbackNamedPipe(const void *baton, uint16_t port) { 700 const char *named_pipe = (const char *)baton; 701 if (named_pipe && named_pipe[0]) { 702 int fd = ::open(named_pipe, O_WRONLY); 703 if (fd > -1) { 704 char port_str[64]; 705 const ssize_t port_str_len = 706 ::snprintf(port_str, sizeof(port_str), "%u", port); 707 // Write the port number as a C string with the NULL terminator 708 ::write(fd, port_str, port_str_len + 1); 709 close(fd); 710 } 711 } 712 } 713 714 static int ConnectRemote(RNBRemote *remote, const char *host, int port, 715 bool reverse_connect, const char *named_pipe_path, 716 const char *unix_socket_name) { 717 if (!remote->Comm().IsConnected()) { 718 if (reverse_connect) { 719 if (port == 0) { 720 DNBLogThreaded( 721 "error: invalid port supplied for reverse connection: %i.\n", port); 722 return 0; 723 } 724 if (remote->Comm().Connect(host, port) != rnb_success) { 725 DNBLogThreaded("Failed to reverse connect to %s:%i.\n", host, port); 726 return 0; 727 } 728 } else { 729 if (port != 0) 730 RNBLogSTDOUT("Listening to port %i for a connection from %s...\n", port, 731 host ? host : "127.0.0.1"); 732 if (unix_socket_name && unix_socket_name[0]) { 733 if (remote->Comm().Listen(host, port, PortWasBoundCallbackUnixSocket, 734 unix_socket_name) != rnb_success) { 735 RNBLogSTDERR("Failed to get connection from a remote gdb process.\n"); 736 return 0; 737 } 738 } else { 739 if (remote->Comm().Listen(host, port, PortWasBoundCallbackNamedPipe, 740 named_pipe_path) != rnb_success) { 741 RNBLogSTDERR("Failed to get connection from a remote gdb process.\n"); 742 return 0; 743 } 744 } 745 } 746 remote->StartReadRemoteDataThread(); 747 } 748 return 1; 749 } 750 751 // ASL Logging callback that can be registered with DNBLogSetLogCallback 752 void ASLLogCallback(void *baton, uint32_t flags, const char *format, 753 va_list args) { 754 if (format == NULL) 755 return; 756 static aslmsg g_aslmsg = NULL; 757 if (g_aslmsg == NULL) { 758 g_aslmsg = ::asl_new(ASL_TYPE_MSG); 759 char asl_key_sender[PATH_MAX]; 760 snprintf(asl_key_sender, sizeof(asl_key_sender), "com.apple.%s-%s", 761 DEBUGSERVER_PROGRAM_NAME, DEBUGSERVER_VERSION_STR); 762 ::asl_set(g_aslmsg, ASL_KEY_SENDER, asl_key_sender); 763 } 764 765 int asl_level; 766 if (flags & DNBLOG_FLAG_FATAL) 767 asl_level = ASL_LEVEL_CRIT; 768 else if (flags & DNBLOG_FLAG_ERROR) 769 asl_level = ASL_LEVEL_ERR; 770 else if (flags & DNBLOG_FLAG_WARNING) 771 asl_level = ASL_LEVEL_WARNING; 772 else if (flags & DNBLOG_FLAG_VERBOSE) 773 asl_level = ASL_LEVEL_WARNING; // ASL_LEVEL_INFO; 774 else 775 asl_level = ASL_LEVEL_WARNING; // ASL_LEVEL_DEBUG; 776 777 ::asl_vlog(NULL, g_aslmsg, asl_level, format, args); 778 } 779 780 // FILE based Logging callback that can be registered with 781 // DNBLogSetLogCallback 782 void FileLogCallback(void *baton, uint32_t flags, const char *format, 783 va_list args) { 784 if (baton == NULL || format == NULL) 785 return; 786 787 ::vfprintf((FILE *)baton, format, args); 788 ::fprintf((FILE *)baton, "\n"); 789 ::fflush((FILE *)baton); 790 } 791 792 void show_version_and_exit(int exit_code) { 793 printf("%s-%s for %s.\n", DEBUGSERVER_PROGRAM_NAME, DEBUGSERVER_VERSION_STR, 794 RNB_ARCH); 795 exit(exit_code); 796 } 797 798 void show_usage_and_exit(int exit_code) { 799 RNBLogSTDERR( 800 "Usage:\n %s host:port [program-name program-arg1 program-arg2 ...]\n", 801 DEBUGSERVER_PROGRAM_NAME); 802 RNBLogSTDERR(" %s /path/file [program-name program-arg1 program-arg2 ...]\n", 803 DEBUGSERVER_PROGRAM_NAME); 804 RNBLogSTDERR(" %s host:port --attach=<pid>\n", DEBUGSERVER_PROGRAM_NAME); 805 RNBLogSTDERR(" %s /path/file --attach=<pid>\n", DEBUGSERVER_PROGRAM_NAME); 806 RNBLogSTDERR(" %s host:port --attach=<process_name>\n", 807 DEBUGSERVER_PROGRAM_NAME); 808 RNBLogSTDERR(" %s /path/file --attach=<process_name>\n", 809 DEBUGSERVER_PROGRAM_NAME); 810 exit(exit_code); 811 } 812 813 // option descriptors for getopt_long_only() 814 static struct option g_long_options[] = { 815 {"attach", required_argument, NULL, 'a'}, 816 {"arch", required_argument, NULL, 'A'}, 817 {"debug", no_argument, NULL, 'g'}, 818 {"kill-on-error", no_argument, NULL, 'K'}, 819 {"verbose", no_argument, NULL, 'v'}, 820 {"version", no_argument, NULL, 'V'}, 821 {"lockdown", no_argument, &g_lockdown_opt, 1}, // short option "-k" 822 {"applist", no_argument, &g_applist_opt, 1}, // short option "-t" 823 {"log-file", required_argument, NULL, 'l'}, 824 {"log-flags", required_argument, NULL, 'f'}, 825 {"launch", required_argument, NULL, 'x'}, // Valid values are "auto", 826 // "posix-spawn", "fork-exec", 827 // "springboard" (arm only) 828 {"waitfor", required_argument, NULL, 829 'w'}, // Wait for a process whose name starts with ARG 830 {"waitfor-interval", required_argument, NULL, 831 'i'}, // Time in usecs to wait between sampling the pid list when waiting 832 // for a process by name 833 {"waitfor-duration", required_argument, NULL, 834 'd'}, // The time in seconds to wait for a process to show up by name 835 {"native-regs", no_argument, NULL, 'r'}, // Specify to use the native 836 // registers instead of the gdb 837 // defaults for the architecture. 838 {"stdio-path", required_argument, NULL, 839 's'}, // Set the STDIO path to be used when launching applications (STDIN, 840 // STDOUT and STDERR) (only if debugserver launches the process) 841 {"stdin-path", required_argument, NULL, 842 'I'}, // Set the STDIN path to be used when launching applications (only if 843 // debugserver launches the process) 844 {"stdout-path", required_argument, NULL, 845 'O'}, // Set the STDOUT path to be used when launching applications (only 846 // if debugserver launches the process) 847 {"stderr-path", required_argument, NULL, 848 'E'}, // Set the STDERR path to be used when launching applications (only 849 // if debugserver launches the process) 850 {"no-stdio", no_argument, NULL, 851 'n'}, // Do not set up any stdio (perhaps the program is a GUI program) 852 // (only if debugserver launches the process) 853 {"setsid", no_argument, NULL, 854 'S'}, // call setsid() to make debugserver run in its own session 855 {"disable-aslr", no_argument, NULL, 'D'}, // Use _POSIX_SPAWN_DISABLE_ASLR 856 // to avoid shared library 857 // randomization 858 {"working-dir", required_argument, NULL, 859 'W'}, // The working directory that the inferior process should have (only 860 // if debugserver launches the process) 861 {"platform", required_argument, NULL, 862 'p'}, // Put this executable into a remote platform mode 863 {"unix-socket", required_argument, NULL, 864 'u'}, // If we need to handshake with our parent process, an option will be 865 // passed down that specifies a unix socket name to use 866 {"fd", required_argument, NULL, 867 '2'}, // A file descriptor was passed to this process when spawned that 868 // is already open and ready for communication 869 {"named-pipe", required_argument, NULL, 'P'}, 870 {"reverse-connect", no_argument, NULL, 'R'}, 871 {"env", required_argument, NULL, 872 'e'}, // When debugserver launches the process, set a single environment 873 // entry as specified by the option value ("./debugserver -e FOO=1 -e 874 // BAR=2 localhost:1234 -- /bin/ls") 875 {"forward-env", no_argument, NULL, 876 'F'}, // When debugserver launches the process, forward debugserver's 877 // current environment variables to the child process ("./debugserver 878 // -F localhost:1234 -- /bin/ls" 879 {NULL, 0, NULL, 0}}; 880 881 int communication_fd = -1; 882 883 // main 884 int main(int argc, char *argv[]) { 885 // If debugserver is launched with DYLD_INSERT_LIBRARIES, unset it so we 886 // don't spawn child processes with this enabled. 887 unsetenv("DYLD_INSERT_LIBRARIES"); 888 889 const char *argv_sub_zero = 890 argv[0]; // save a copy of argv[0] for error reporting post-launch 891 892 #if defined(__APPLE__) 893 pthread_setname_np("main thread"); 894 #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__) 895 struct sched_param thread_param; 896 int thread_sched_policy; 897 if (pthread_getschedparam(pthread_self(), &thread_sched_policy, 898 &thread_param) == 0) { 899 thread_param.sched_priority = 47; 900 pthread_setschedparam(pthread_self(), thread_sched_policy, &thread_param); 901 } 902 903 ::proc_set_wakemon_params( 904 getpid(), 500, 905 0); // Allow up to 500 wakeups/sec to avoid EXC_RESOURCE for normal use. 906 #endif 907 #endif 908 909 g_isatty = ::isatty(STDIN_FILENO); 910 911 // ::printf ("uid=%u euid=%u gid=%u egid=%u\n", 912 // getuid(), 913 // geteuid(), 914 // getgid(), 915 // getegid()); 916 917 // signal (SIGINT, signal_handler); 918 signal(SIGPIPE, signal_handler); 919 signal(SIGHUP, signal_handler); 920 921 // We're always sitting in waitpid or kevent waiting on our target process' 922 // death, 923 // we don't need no stinking SIGCHLD's... 924 925 sigset_t sigset; 926 sigemptyset(&sigset); 927 sigaddset(&sigset, SIGCHLD); 928 sigprocmask(SIG_BLOCK, &sigset, NULL); 929 930 g_remoteSP = std::make_shared<RNBRemote>(); 931 932 RNBRemote *remote = g_remoteSP.get(); 933 if (remote == NULL) { 934 RNBLogSTDERR("error: failed to create a remote connection class\n"); 935 return -1; 936 } 937 938 RNBContext &ctx = remote->Context(); 939 940 int i; 941 int attach_pid = INVALID_NUB_PROCESS; 942 943 FILE *log_file = NULL; 944 uint32_t log_flags = 0; 945 // Parse our options 946 int ch; 947 int long_option_index = 0; 948 int debug = 0; 949 std::string compile_options; 950 std::string waitfor_pid_name; // Wait for a process that starts with this name 951 std::string attach_pid_name; 952 std::string arch_name; 953 std::string working_dir; // The new working directory to use for the inferior 954 std::string unix_socket_name; // If we need to handshake with our parent 955 // process, an option will be passed down that 956 // specifies a unix socket name to use 957 std::string named_pipe_path; // If we need to handshake with our parent 958 // process, an option will be passed down that 959 // specifies a named pipe to use 960 useconds_t waitfor_interval = 1000; // Time in usecs between process lists 961 // polls when waiting for a process by 962 // name, default 1 msec. 963 useconds_t waitfor_duration = 964 0; // Time in seconds to wait for a process by name, 0 means wait forever. 965 bool no_stdio = false; 966 bool reverse_connect = false; // Set to true by an option to indicate we 967 // should reverse connect to the host:port 968 // supplied as the first debugserver argument 969 970 #if !defined(DNBLOG_ENABLED) 971 compile_options += "(no-logging) "; 972 #endif 973 974 RNBRunLoopMode start_mode = eRNBRunLoopModeExit; 975 976 char short_options[512]; 977 uint32_t short_options_idx = 0; 978 979 // Handle the two case that don't have short options in g_long_options 980 short_options[short_options_idx++] = 'k'; 981 short_options[short_options_idx++] = 't'; 982 983 for (i = 0; g_long_options[i].name != NULL; ++i) { 984 if (isalpha(g_long_options[i].val)) { 985 short_options[short_options_idx++] = g_long_options[i].val; 986 switch (g_long_options[i].has_arg) { 987 default: 988 case no_argument: 989 break; 990 991 case optional_argument: 992 short_options[short_options_idx++] = ':'; 993 short_options[short_options_idx++] = ':'; 994 break; 995 case required_argument: 996 short_options[short_options_idx++] = ':'; 997 break; 998 } 999 } 1000 } 1001 // NULL terminate the short option string. 1002 short_options[short_options_idx++] = '\0'; 1003 1004 #if __GLIBC__ 1005 optind = 0; 1006 #else 1007 optreset = 1; 1008 optind = 1; 1009 #endif 1010 1011 bool forward_env = false; 1012 while ((ch = getopt_long_only(argc, argv, short_options, g_long_options, 1013 &long_option_index)) != -1) { 1014 DNBLogDebug("option: ch == %c (0x%2.2x) --%s%c%s\n", ch, (uint8_t)ch, 1015 g_long_options[long_option_index].name, 1016 g_long_options[long_option_index].has_arg ? '=' : ' ', 1017 optarg ? optarg : ""); 1018 switch (ch) { 1019 case 0: // Any optional that auto set themselves will return 0 1020 break; 1021 1022 case 'A': 1023 if (optarg && optarg[0]) 1024 arch_name.assign(optarg); 1025 break; 1026 1027 case 'a': 1028 if (optarg && optarg[0]) { 1029 if (isdigit(optarg[0])) { 1030 char *end = NULL; 1031 attach_pid = static_cast<int>(strtoul(optarg, &end, 0)); 1032 if (end == NULL || *end != '\0') { 1033 RNBLogSTDERR("error: invalid pid option '%s'\n", optarg); 1034 exit(4); 1035 } 1036 } else { 1037 attach_pid_name = optarg; 1038 } 1039 start_mode = eRNBRunLoopModeInferiorAttaching; 1040 } 1041 break; 1042 1043 // --waitfor=NAME 1044 case 'w': 1045 if (optarg && optarg[0]) { 1046 waitfor_pid_name = optarg; 1047 start_mode = eRNBRunLoopModeInferiorAttaching; 1048 } 1049 break; 1050 1051 // --waitfor-interval=USEC 1052 case 'i': 1053 if (optarg && optarg[0]) { 1054 char *end = NULL; 1055 waitfor_interval = static_cast<useconds_t>(strtoul(optarg, &end, 0)); 1056 if (end == NULL || *end != '\0') { 1057 RNBLogSTDERR("error: invalid waitfor-interval option value '%s'.\n", 1058 optarg); 1059 exit(6); 1060 } 1061 } 1062 break; 1063 1064 // --waitfor-duration=SEC 1065 case 'd': 1066 if (optarg && optarg[0]) { 1067 char *end = NULL; 1068 waitfor_duration = static_cast<useconds_t>(strtoul(optarg, &end, 0)); 1069 if (end == NULL || *end != '\0') { 1070 RNBLogSTDERR("error: invalid waitfor-duration option value '%s'.\n", 1071 optarg); 1072 exit(7); 1073 } 1074 } 1075 break; 1076 1077 case 'K': 1078 g_detach_on_error = false; 1079 break; 1080 case 'W': 1081 if (optarg && optarg[0]) 1082 working_dir.assign(optarg); 1083 break; 1084 1085 case 'x': 1086 if (optarg && optarg[0]) { 1087 if (strcasecmp(optarg, "auto") == 0) 1088 g_launch_flavor = eLaunchFlavorDefault; 1089 else if (strcasestr(optarg, "posix") == optarg) 1090 g_launch_flavor = eLaunchFlavorPosixSpawn; 1091 else if (strcasestr(optarg, "fork") == optarg) 1092 g_launch_flavor = eLaunchFlavorForkExec; 1093 #ifdef WITH_SPRINGBOARD 1094 else if (strcasestr(optarg, "spring") == optarg) 1095 g_launch_flavor = eLaunchFlavorSpringBoard; 1096 #endif 1097 #ifdef WITH_BKS 1098 else if (strcasestr(optarg, "backboard") == optarg) 1099 g_launch_flavor = eLaunchFlavorBKS; 1100 #endif 1101 #ifdef WITH_FBS 1102 else if (strcasestr(optarg, "frontboard") == optarg) 1103 g_launch_flavor = eLaunchFlavorFBS; 1104 #endif 1105 1106 else { 1107 RNBLogSTDERR("error: invalid TYPE for the --launch=TYPE (-x TYPE) " 1108 "option: '%s'\n", 1109 optarg); 1110 RNBLogSTDERR("Valid values TYPE are:\n"); 1111 RNBLogSTDERR( 1112 " auto Auto-detect the best launch method to use.\n"); 1113 RNBLogSTDERR( 1114 " posix Launch the executable using posix_spawn.\n"); 1115 RNBLogSTDERR( 1116 " fork Launch the executable using fork and exec.\n"); 1117 #ifdef WITH_SPRINGBOARD 1118 RNBLogSTDERR( 1119 " spring Launch the executable through Springboard.\n"); 1120 #endif 1121 #ifdef WITH_BKS 1122 RNBLogSTDERR(" backboard Launch the executable through BackBoard " 1123 "Services.\n"); 1124 #endif 1125 #ifdef WITH_FBS 1126 RNBLogSTDERR(" frontboard Launch the executable through FrontBoard " 1127 "Services.\n"); 1128 #endif 1129 exit(5); 1130 } 1131 } 1132 break; 1133 1134 case 'l': // Set Log File 1135 if (optarg && optarg[0]) { 1136 if (strcasecmp(optarg, "stdout") == 0) 1137 log_file = stdout; 1138 else if (strcasecmp(optarg, "stderr") == 0) 1139 log_file = stderr; 1140 else { 1141 log_file = fopen(optarg, "w"); 1142 if (log_file != NULL) 1143 setlinebuf(log_file); 1144 } 1145 1146 if (log_file == NULL) { 1147 const char *errno_str = strerror(errno); 1148 RNBLogSTDERR( 1149 "Failed to open log file '%s' for writing: errno = %i (%s)", 1150 optarg, errno, errno_str ? errno_str : "unknown error"); 1151 } 1152 } 1153 break; 1154 1155 case 'f': // Log Flags 1156 if (optarg && optarg[0]) 1157 log_flags = static_cast<uint32_t>(strtoul(optarg, NULL, 0)); 1158 break; 1159 1160 case 'g': 1161 debug = 1; 1162 DNBLogSetDebug(debug); 1163 break; 1164 1165 case 't': 1166 g_applist_opt = 1; 1167 break; 1168 1169 case 'k': 1170 g_lockdown_opt = 1; 1171 break; 1172 1173 case 'r': 1174 // Do nothing, native regs is the default these days 1175 break; 1176 1177 case 'R': 1178 reverse_connect = true; 1179 break; 1180 case 'v': 1181 DNBLogSetVerbose(1); 1182 break; 1183 1184 case 'V': 1185 show_version_and_exit(0); 1186 break; 1187 1188 case 's': 1189 ctx.GetSTDIN().assign(optarg); 1190 ctx.GetSTDOUT().assign(optarg); 1191 ctx.GetSTDERR().assign(optarg); 1192 break; 1193 1194 case 'I': 1195 ctx.GetSTDIN().assign(optarg); 1196 break; 1197 1198 case 'O': 1199 ctx.GetSTDOUT().assign(optarg); 1200 break; 1201 1202 case 'E': 1203 ctx.GetSTDERR().assign(optarg); 1204 break; 1205 1206 case 'n': 1207 no_stdio = true; 1208 break; 1209 1210 case 'S': 1211 // Put debugserver into a new session. Terminals group processes 1212 // into sessions and when a special terminal key sequences 1213 // (like control+c) are typed they can cause signals to go out to 1214 // all processes in a session. Using this --setsid (-S) option 1215 // will cause debugserver to run in its own sessions and be free 1216 // from such issues. 1217 // 1218 // This is useful when debugserver is spawned from a command 1219 // line application that uses debugserver to do the debugging, 1220 // yet that application doesn't want debugserver receiving the 1221 // signals sent to the session (i.e. dying when anyone hits ^C). 1222 setsid(); 1223 break; 1224 case 'D': 1225 g_disable_aslr = 1; 1226 break; 1227 1228 case 'p': 1229 start_mode = eRNBRunLoopModePlatformMode; 1230 break; 1231 1232 case 'u': 1233 unix_socket_name.assign(optarg); 1234 break; 1235 1236 case 'P': 1237 named_pipe_path.assign(optarg); 1238 break; 1239 1240 case 'e': 1241 // Pass a single specified environment variable down to the process that 1242 // gets launched 1243 remote->Context().PushEnvironment(optarg); 1244 break; 1245 1246 case 'F': 1247 forward_env = true; 1248 break; 1249 1250 case '2': 1251 // File descriptor passed to this process during fork/exec and is already 1252 // open and ready for communication. 1253 communication_fd = atoi(optarg); 1254 break; 1255 } 1256 } 1257 1258 if (arch_name.empty()) { 1259 #if defined(__arm__) 1260 arch_name.assign("arm"); 1261 #endif 1262 } else { 1263 DNBSetArchitecture(arch_name.c_str()); 1264 } 1265 1266 // if (arch_name.empty()) 1267 // { 1268 // fprintf(stderr, "error: no architecture was specified\n"); 1269 // exit (8); 1270 // } 1271 // Skip any options we consumed with getopt_long_only 1272 argc -= optind; 1273 argv += optind; 1274 1275 if (!working_dir.empty()) { 1276 if (remote->Context().SetWorkingDirectory(working_dir.c_str()) == false) { 1277 RNBLogSTDERR("error: working directory doesn't exist '%s'.\n", 1278 working_dir.c_str()); 1279 exit(8); 1280 } 1281 } 1282 1283 remote->Context().SetDetachOnError(g_detach_on_error); 1284 1285 remote->Initialize(); 1286 1287 // It is ok for us to set NULL as the logfile (this will disable any logging) 1288 1289 if (log_file != NULL) { 1290 DNBLogSetLogCallback(FileLogCallback, log_file); 1291 // If our log file was set, yet we have no log flags, log everything! 1292 if (log_flags == 0) 1293 log_flags = LOG_ALL | LOG_RNB_ALL; 1294 1295 DNBLogSetLogMask(log_flags); 1296 } else { 1297 // Enable DNB logging 1298 1299 // if os_log() support is available, log through that. 1300 auto log_callback = OsLogger::GetLogFunction(); 1301 if (log_callback) { 1302 DNBLogSetLogCallback(log_callback, nullptr); 1303 DNBLog("debugserver will use os_log for internal logging."); 1304 } else { 1305 // Fall back to ASL support. 1306 DNBLogSetLogCallback(ASLLogCallback, NULL); 1307 DNBLog("debugserver will use ASL for internal logging."); 1308 } 1309 DNBLogSetLogMask(log_flags); 1310 } 1311 1312 if (DNBLogEnabled()) { 1313 for (i = 0; i < argc; i++) 1314 DNBLogDebug("argv[%i] = %s", i, argv[i]); 1315 } 1316 1317 // as long as we're dropping remotenub in as a replacement for gdbserver, 1318 // explicitly note that this is not gdbserver. 1319 1320 RNBLogSTDOUT("%s-%s %sfor %s.\n", DEBUGSERVER_PROGRAM_NAME, 1321 DEBUGSERVER_VERSION_STR, compile_options.c_str(), RNB_ARCH); 1322 1323 std::string host; 1324 int port = INT32_MAX; 1325 char str[PATH_MAX]; 1326 str[0] = '\0'; 1327 1328 if (g_lockdown_opt == 0 && g_applist_opt == 0 && communication_fd == -1) { 1329 // Make sure we at least have port 1330 if (argc < 1) { 1331 show_usage_and_exit(1); 1332 } 1333 // accept 'localhost:' prefix on port number 1334 std::string host_specifier = argv[0]; 1335 auto colon_location = host_specifier.rfind(':'); 1336 if (colon_location != std::string::npos) { 1337 host = host_specifier.substr(0, colon_location); 1338 std::string port_str = 1339 host_specifier.substr(colon_location + 1, std::string::npos); 1340 char *end_ptr; 1341 port = strtoul(port_str.c_str(), &end_ptr, 0); 1342 if (end_ptr < port_str.c_str() + port_str.size()) 1343 show_usage_and_exit(2); 1344 if (host.front() == '[' && host.back() == ']') 1345 host = host.substr(1, host.size() - 2); 1346 DNBLogDebug("host = '%s' port = %i", host.c_str(), port); 1347 } else { 1348 // No hostname means "localhost" 1349 int items_scanned = ::sscanf(argv[0], "%i", &port); 1350 if (items_scanned == 1) { 1351 host = "127.0.0.1"; 1352 DNBLogDebug("host = '%s' port = %i", host.c_str(), port); 1353 } else if (argv[0][0] == '/') { 1354 port = INT32_MAX; 1355 strlcpy(str, argv[0], sizeof(str)); 1356 } else { 1357 show_usage_and_exit(2); 1358 } 1359 } 1360 1361 // We just used the 'host:port' or the '/path/file' arg... 1362 argc--; 1363 argv++; 1364 } 1365 1366 // If we know we're waiting to attach, we don't need any of this other info. 1367 if (start_mode != eRNBRunLoopModeInferiorAttaching && 1368 start_mode != eRNBRunLoopModePlatformMode) { 1369 if (argc == 0 || g_lockdown_opt) { 1370 if (g_lockdown_opt != 0) { 1371 // Work around for SIGPIPE crashes due to posix_spawn issue. 1372 // We have to close STDOUT and STDERR, else the first time we 1373 // try and do any, we get SIGPIPE and die as posix_spawn is 1374 // doing bad things with our file descriptors at the moment. 1375 int null = open("/dev/null", O_RDWR); 1376 dup2(null, STDOUT_FILENO); 1377 dup2(null, STDERR_FILENO); 1378 } else if (g_applist_opt != 0) { 1379 // List all applications we are able to see 1380 std::string applist_plist; 1381 int err = ListApplications(applist_plist, false, false); 1382 if (err == 0) { 1383 fputs(applist_plist.c_str(), stdout); 1384 } else { 1385 RNBLogSTDERR("error: ListApplications returned error %i\n", err); 1386 } 1387 // Exit with appropriate error if we were asked to list the applications 1388 // with no other args were given (and we weren't trying to do this over 1389 // lockdown) 1390 return err; 1391 } 1392 1393 DNBLogDebug("Get args from remote protocol..."); 1394 start_mode = eRNBRunLoopModeGetStartModeFromRemoteProtocol; 1395 } else { 1396 start_mode = eRNBRunLoopModeInferiorLaunching; 1397 // Fill in the argv array in the context from the rest of our args. 1398 // Skip the name of this executable and the port number 1399 for (int i = 0; i < argc; i++) { 1400 DNBLogDebug("inferior_argv[%i] = '%s'", i, argv[i]); 1401 ctx.PushArgument(argv[i]); 1402 } 1403 } 1404 } 1405 1406 if (start_mode == eRNBRunLoopModeExit) 1407 return -1; 1408 1409 if (forward_env || start_mode == eRNBRunLoopModeInferiorLaunching) { 1410 // Pass the current environment down to the process that gets launched 1411 // This happens automatically in the "launching" mode. For the rest, we 1412 // only do that if the user explicitly requested this via --forward-env 1413 // argument. 1414 char **host_env = *_NSGetEnviron(); 1415 char *env_entry; 1416 size_t i; 1417 for (i = 0; (env_entry = host_env[i]) != NULL; ++i) 1418 remote->Context().PushEnvironmentIfNeeded(env_entry); 1419 } 1420 1421 RNBRunLoopMode mode = start_mode; 1422 char err_str[1024] = {'\0'}; 1423 1424 while (mode != eRNBRunLoopModeExit) { 1425 switch (mode) { 1426 case eRNBRunLoopModeGetStartModeFromRemoteProtocol: 1427 #ifdef WITH_LOCKDOWN 1428 if (g_lockdown_opt) { 1429 if (!remote->Comm().IsConnected()) { 1430 if (remote->Comm().ConnectToService() != rnb_success) { 1431 RNBLogSTDERR( 1432 "Failed to get connection from a remote gdb process.\n"); 1433 mode = eRNBRunLoopModeExit; 1434 } else if (g_applist_opt != 0) { 1435 // List all applications we are able to see 1436 std::string applist_plist; 1437 if (ListApplications(applist_plist, false, false) == 0) { 1438 DNBLogDebug("Task list: %s", applist_plist.c_str()); 1439 1440 remote->Comm().Write(applist_plist.c_str(), applist_plist.size()); 1441 // Issue a read that will never yield any data until the other 1442 // side 1443 // closes the socket so this process doesn't just exit and cause 1444 // the 1445 // socket to close prematurely on the other end and cause data 1446 // loss. 1447 std::string buf; 1448 remote->Comm().Read(buf); 1449 } 1450 remote->Comm().Disconnect(false); 1451 mode = eRNBRunLoopModeExit; 1452 break; 1453 } else { 1454 // Start watching for remote packets 1455 remote->StartReadRemoteDataThread(); 1456 } 1457 } 1458 } else 1459 #endif 1460 if (port != INT32_MAX) { 1461 if (!ConnectRemote(remote, host.c_str(), port, reverse_connect, 1462 named_pipe_path.c_str(), unix_socket_name.c_str())) 1463 mode = eRNBRunLoopModeExit; 1464 } else if (str[0] == '/') { 1465 if (remote->Comm().OpenFile(str)) 1466 mode = eRNBRunLoopModeExit; 1467 } else if (communication_fd >= 0) { 1468 // We were passed a file descriptor to use during fork/exec that is 1469 // already open 1470 // in our process, so lets just use it! 1471 if (remote->Comm().useFD(communication_fd)) 1472 mode = eRNBRunLoopModeExit; 1473 else 1474 remote->StartReadRemoteDataThread(); 1475 } 1476 1477 if (mode != eRNBRunLoopModeExit) { 1478 RNBLogSTDOUT("Got a connection, waiting for process information for " 1479 "launching or attaching.\n"); 1480 1481 mode = RNBRunLoopGetStartModeFromRemote(remote); 1482 } 1483 break; 1484 1485 case eRNBRunLoopModeInferiorAttaching: 1486 if (!waitfor_pid_name.empty()) { 1487 // Set our end wait time if we are using a waitfor-duration 1488 // option that may have been specified 1489 struct timespec attach_timeout_abstime, *timeout_ptr = NULL; 1490 if (waitfor_duration != 0) { 1491 DNBTimer::OffsetTimeOfDay(&attach_timeout_abstime, waitfor_duration, 1492 0); 1493 timeout_ptr = &attach_timeout_abstime; 1494 } 1495 nub_launch_flavor_t launch_flavor = g_launch_flavor; 1496 if (launch_flavor == eLaunchFlavorDefault) { 1497 // Our default launch method is posix spawn 1498 launch_flavor = eLaunchFlavorPosixSpawn; 1499 1500 #if defined WITH_FBS 1501 // Check if we have an app bundle, if so launch using SpringBoard. 1502 if (waitfor_pid_name.find(".app") != std::string::npos) { 1503 launch_flavor = eLaunchFlavorFBS; 1504 } 1505 #elif defined WITH_BKS 1506 // Check if we have an app bundle, if so launch using SpringBoard. 1507 if (waitfor_pid_name.find(".app") != std::string::npos) { 1508 launch_flavor = eLaunchFlavorBKS; 1509 } 1510 #elif defined WITH_SPRINGBOARD 1511 // Check if we have an app bundle, if so launch using SpringBoard. 1512 if (waitfor_pid_name.find(".app") != std::string::npos) { 1513 launch_flavor = eLaunchFlavorSpringBoard; 1514 } 1515 #endif 1516 } 1517 1518 ctx.SetLaunchFlavor(launch_flavor); 1519 bool ignore_existing = false; 1520 RNBLogSTDOUT("Waiting to attach to process %s...\n", 1521 waitfor_pid_name.c_str()); 1522 nub_process_t pid = DNBProcessAttachWait( 1523 waitfor_pid_name.c_str(), launch_flavor, ignore_existing, 1524 timeout_ptr, waitfor_interval, err_str, sizeof(err_str)); 1525 g_pid = pid; 1526 1527 if (pid == INVALID_NUB_PROCESS) { 1528 ctx.LaunchStatus().SetError(-1, DNBError::Generic); 1529 if (err_str[0]) 1530 ctx.LaunchStatus().SetErrorString(err_str); 1531 RNBLogSTDERR("error: failed to attach to process named: \"%s\" %s\n", 1532 waitfor_pid_name.c_str(), err_str); 1533 mode = eRNBRunLoopModeExit; 1534 } else { 1535 ctx.SetProcessID(pid); 1536 mode = eRNBRunLoopModeInferiorExecuting; 1537 } 1538 } else if (attach_pid != INVALID_NUB_PROCESS) { 1539 1540 RNBLogSTDOUT("Attaching to process %i...\n", attach_pid); 1541 nub_process_t attached_pid; 1542 mode = RNBRunLoopLaunchAttaching(remote, attach_pid, attached_pid); 1543 if (mode != eRNBRunLoopModeInferiorExecuting) { 1544 const char *error_str = remote->Context().LaunchStatus().AsString(); 1545 RNBLogSTDERR("error: failed to attach process %i: %s\n", attach_pid, 1546 error_str ? error_str : "unknown error."); 1547 mode = eRNBRunLoopModeExit; 1548 } 1549 } else if (!attach_pid_name.empty()) { 1550 struct timespec attach_timeout_abstime, *timeout_ptr = NULL; 1551 if (waitfor_duration != 0) { 1552 DNBTimer::OffsetTimeOfDay(&attach_timeout_abstime, waitfor_duration, 1553 0); 1554 timeout_ptr = &attach_timeout_abstime; 1555 } 1556 1557 RNBLogSTDOUT("Attaching to process %s...\n", attach_pid_name.c_str()); 1558 nub_process_t pid = DNBProcessAttachByName( 1559 attach_pid_name.c_str(), timeout_ptr, err_str, sizeof(err_str)); 1560 g_pid = pid; 1561 if (pid == INVALID_NUB_PROCESS) { 1562 ctx.LaunchStatus().SetError(-1, DNBError::Generic); 1563 if (err_str[0]) 1564 ctx.LaunchStatus().SetErrorString(err_str); 1565 RNBLogSTDERR("error: failed to attach to process named: \"%s\" %s\n", 1566 waitfor_pid_name.c_str(), err_str); 1567 mode = eRNBRunLoopModeExit; 1568 } else { 1569 ctx.SetProcessID(pid); 1570 mode = eRNBRunLoopModeInferiorExecuting; 1571 } 1572 1573 } else { 1574 RNBLogSTDERR( 1575 "error: asked to attach with empty name and invalid PID.\n"); 1576 mode = eRNBRunLoopModeExit; 1577 } 1578 1579 if (mode != eRNBRunLoopModeExit) { 1580 if (port != INT32_MAX) { 1581 if (!ConnectRemote(remote, host.c_str(), port, reverse_connect, 1582 named_pipe_path.c_str(), unix_socket_name.c_str())) 1583 mode = eRNBRunLoopModeExit; 1584 } else if (str[0] == '/') { 1585 if (remote->Comm().OpenFile(str)) 1586 mode = eRNBRunLoopModeExit; 1587 } else if (communication_fd >= 0) { 1588 // We were passed a file descriptor to use during fork/exec that is 1589 // already open 1590 // in our process, so lets just use it! 1591 if (remote->Comm().useFD(communication_fd)) 1592 mode = eRNBRunLoopModeExit; 1593 else 1594 remote->StartReadRemoteDataThread(); 1595 } 1596 1597 if (mode != eRNBRunLoopModeExit) 1598 RNBLogSTDOUT("Waiting for debugger instructions for process %d.\n", 1599 attach_pid); 1600 } 1601 break; 1602 1603 case eRNBRunLoopModeInferiorLaunching: { 1604 mode = RNBRunLoopLaunchInferior(remote, ctx.GetSTDINPath(), 1605 ctx.GetSTDOUTPath(), ctx.GetSTDERRPath(), 1606 no_stdio); 1607 1608 if (mode == eRNBRunLoopModeInferiorExecuting) { 1609 if (port != INT32_MAX) { 1610 if (!ConnectRemote(remote, host.c_str(), port, reverse_connect, 1611 named_pipe_path.c_str(), unix_socket_name.c_str())) 1612 mode = eRNBRunLoopModeExit; 1613 } else if (str[0] == '/') { 1614 if (remote->Comm().OpenFile(str)) 1615 mode = eRNBRunLoopModeExit; 1616 } else if (communication_fd >= 0) { 1617 // We were passed a file descriptor to use during fork/exec that is 1618 // already open 1619 // in our process, so lets just use it! 1620 if (remote->Comm().useFD(communication_fd)) 1621 mode = eRNBRunLoopModeExit; 1622 else 1623 remote->StartReadRemoteDataThread(); 1624 } 1625 1626 if (mode != eRNBRunLoopModeExit) { 1627 const char *proc_name = "<unknown>"; 1628 if (ctx.ArgumentCount() > 0) 1629 proc_name = ctx.ArgumentAtIndex(0); 1630 RNBLogSTDOUT("Got a connection, launched process %s (pid = %d).\n", 1631 proc_name, ctx.ProcessID()); 1632 } 1633 } else { 1634 const char *error_str = remote->Context().LaunchStatus().AsString(); 1635 RNBLogSTDERR("error: failed to launch process %s: %s\n", argv_sub_zero, 1636 error_str ? error_str : "unknown error."); 1637 } 1638 } break; 1639 1640 case eRNBRunLoopModeInferiorExecuting: 1641 mode = RNBRunLoopInferiorExecuting(remote); 1642 break; 1643 1644 case eRNBRunLoopModePlatformMode: 1645 if (port != INT32_MAX) { 1646 if (!ConnectRemote(remote, host.c_str(), port, reverse_connect, 1647 named_pipe_path.c_str(), unix_socket_name.c_str())) 1648 mode = eRNBRunLoopModeExit; 1649 } else if (str[0] == '/') { 1650 if (remote->Comm().OpenFile(str)) 1651 mode = eRNBRunLoopModeExit; 1652 } else if (communication_fd >= 0) { 1653 // We were passed a file descriptor to use during fork/exec that is 1654 // already open 1655 // in our process, so lets just use it! 1656 if (remote->Comm().useFD(communication_fd)) 1657 mode = eRNBRunLoopModeExit; 1658 else 1659 remote->StartReadRemoteDataThread(); 1660 } 1661 1662 if (mode != eRNBRunLoopModeExit) 1663 mode = RNBRunLoopPlatform(remote); 1664 break; 1665 1666 default: 1667 mode = eRNBRunLoopModeExit; 1668 break; 1669 case eRNBRunLoopModeExit: 1670 break; 1671 } 1672 } 1673 1674 remote->StopReadRemoteDataThread(); 1675 remote->Context().SetProcessID(INVALID_NUB_PROCESS); 1676 RNBLogSTDOUT("Exiting.\n"); 1677 1678 return 0; 1679 } 1680