1 //===-- debugserver.cpp -----------------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
12 #include <crt_externs.h>
15 #include <netinet/in.h>
16 #include <netinet/tcp.h>
18 #include <sys/select.h>
19 #include <sys/socket.h>
20 #include <sys/sysctl.h>
21 #include <sys/types.h>
27 #if defined(__APPLE__)
29 extern "C" int proc_set_wakemon_params(pid_t
, int,
30 int); // <libproc_internal.h> SPI
38 #include "PseudoTerminal.h"
39 #include "RNBContext.h"
40 #include "RNBRemote.h"
41 #include "RNBServices.h"
42 #include "RNBSocket.h"
43 #include "SysSignal.h"
45 // Global PID in case we get a signal and need to stop the process...
46 nub_process_t g_pid
= INVALID_NUB_PROCESS
;
48 // Run loop modes which determine which run loop function will be called
50 eRNBRunLoopModeInvalid
= 0,
51 eRNBRunLoopModeGetStartModeFromRemoteProtocol
,
52 eRNBRunLoopModeInferiorAttaching
,
53 eRNBRunLoopModeInferiorLaunching
,
54 eRNBRunLoopModeInferiorExecuting
,
55 eRNBRunLoopModePlatformMode
,
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;
67 bool g_detach_on_error
= true;
69 #define RNBLogSTDOUT(fmt, ...) \
72 fprintf(stdout, fmt, ##__VA_ARGS__); \
74 _DNBLog(0, fmt, ##__VA_ARGS__); \
77 #define RNBLogSTDERR(fmt, ...) \
80 fprintf(stderr, fmt, ##__VA_ARGS__); \
82 _DNBLog(0, fmt, ##__VA_ARGS__); \
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
) {
94 RNBContext
&ctx
= remote
->Context();
95 uint32_t event_mask
= RNBContext::event_read_packet_available
|
96 RNBContext::event_read_thread_exiting
;
98 // Spin waiting to get the A packet.
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
);
108 if (set_events
& RNBContext::event_read_thread_exiting
) {
109 RNBLogSTDERR("error: packet read thread exited.\n");
110 return eRNBRunLoopModeExit
;
113 if (set_events
& RNBContext::event_read_packet_available
) {
114 rnb_err_t err
= rnb_err
;
115 RNBRemote::PacketEnum type
;
117 err
= remote
->HandleReceivedPacket(&type
);
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
;
126 RNBLogSTDERR("error: attach failed.\n");
127 return eRNBRunLoopModeExit
;
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
;
137 } else if (err
== rnb_not_connected
) {
138 RNBLogSTDERR("error: connection lost.\n");
139 return eRNBRunLoopModeExit
;
141 // a catch all for any other gdb remote packets that failed
142 DNBLogThreadedIf(LOG_RNB_MINIMAL
, "%s Error getting packet.",
147 DNBLogThreadedIf(LOG_RNB_MINIMAL
, "#### %s", __FUNCTION__
);
149 DNBLogThreadedIf(LOG_RNB_MINIMAL
,
150 "%s Connection closed before getting \"A\" packet.",
152 return eRNBRunLoopModeExit
;
156 return eRNBRunLoopModeExit
;
159 static nub_launch_flavor_t
default_launch_flavor(const char *app_name
) {
160 #if defined(WITH_FBS) || defined(WITH_BKS) || defined(WITH_SPRINGBOARD)
161 // Check the name to see if it ends with .app
162 auto is_dot_app
= [](const char *app_name
) {
163 size_t len
= strlen(app_name
);
167 if (app_name
[len
- 4] == '.' && app_name
[len
- 3] == 'a' &&
168 app_name
[len
- 2] == 'p' && app_name
[len
- 1] == 'p')
173 if (is_dot_app(app_name
)) {
175 // Check if we have an app bundle, if so launch using FrontBoard Services.
176 return eLaunchFlavorFBS
;
177 #elif defined WITH_BKS
178 // Check if we have an app bundle, if so launch using BackBoard Services.
179 return eLaunchFlavorBKS
;
180 #elif defined WITH_SPRINGBOARD
181 // Check if we have an app bundle, if so launch using SpringBoard.
182 return eLaunchFlavorSpringBoard
;
187 // Our default launch method is posix spawn
188 return eLaunchFlavorPosixSpawn
;
191 // This run loop mode will wait for the process to launch and hit its
192 // entry point. It will currently ignore all events except for the
193 // process state changed event, where it watches for the process stopped
194 // or crash process state.
195 RNBRunLoopMode
RNBRunLoopLaunchInferior(RNBRemote
*remote
,
196 const char *stdin_path
,
197 const char *stdout_path
,
198 const char *stderr_path
,
200 RNBContext
&ctx
= remote
->Context();
202 // The Process stuff takes a c array, the RNBContext has a vector...
203 // So make up a c array.
205 DNBLogThreadedIf(LOG_RNB_MINIMAL
, "%s Launching '%s'...", __FUNCTION__
,
206 ctx
.ArgumentAtIndex(0));
208 size_t inferior_argc
= ctx
.ArgumentCount();
209 // Initialize inferior_argv with inferior_argc + 1 NULLs
210 std::vector
<const char *> inferior_argv(inferior_argc
+ 1, NULL
);
213 for (i
= 0; i
< inferior_argc
; i
++)
214 inferior_argv
[i
] = ctx
.ArgumentAtIndex(i
);
216 // Pass the environment array the same way:
218 size_t inferior_envc
= ctx
.EnvironmentCount();
219 // Initialize inferior_argv with inferior_argc + 1 NULLs
220 std::vector
<const char *> inferior_envp(inferior_envc
+ 1, NULL
);
222 for (i
= 0; i
< inferior_envc
; i
++)
223 inferior_envp
[i
] = ctx
.EnvironmentAtIndex(i
);
225 // Our launch type hasn't been set to anything concrete, so we need to
226 // figure our how we are going to launch automatically.
228 nub_launch_flavor_t launch_flavor
= g_launch_flavor
;
229 if (launch_flavor
== eLaunchFlavorDefault
)
230 launch_flavor
= default_launch_flavor(inferior_argv
[0]);
232 ctx
.SetLaunchFlavor(launch_flavor
);
233 char resolved_path
[PATH_MAX
];
235 // If we fail to resolve the path to our executable, then just use what we
236 // were given and hope for the best
237 if (!DNBResolveExecutablePath(inferior_argv
[0], resolved_path
,
238 sizeof(resolved_path
)))
239 ::strlcpy(resolved_path
, inferior_argv
[0], sizeof(resolved_path
));
241 char launch_err_str
[PATH_MAX
];
242 launch_err_str
[0] = '\0';
244 (ctx
.GetWorkingDirPath() != NULL
? ctx
.GetWorkingDirPath()
245 : ctx
.GetWorkingDirectory());
246 const char *process_event
= ctx
.GetProcessEvent();
247 nub_process_t pid
= DNBProcessLaunch(
248 &ctx
, resolved_path
, &inferior_argv
[0], &inferior_envp
[0], cwd
,
249 stdin_path
, stdout_path
, stderr_path
, no_stdio
, g_disable_aslr
,
250 process_event
, launch_err_str
, sizeof(launch_err_str
));
254 if (pid
== INVALID_NUB_PROCESS
&& strlen(launch_err_str
) > 0) {
255 DNBLogThreaded("%s DNBProcessLaunch() returned error: '%s'", __FUNCTION__
,
257 ctx
.LaunchStatus().SetError(-1, DNBError::Generic
);
258 ctx
.LaunchStatus().SetErrorString(launch_err_str
);
259 } else if (pid
== INVALID_NUB_PROCESS
) {
261 "%s DNBProcessLaunch() failed to launch process, unknown failure",
263 ctx
.LaunchStatus().SetError(-1, DNBError::Generic
);
264 ctx
.LaunchStatus().SetErrorString("<unknown failure>");
266 ctx
.LaunchStatus().Clear();
269 if (remote
->Comm().IsConnected()) {
270 // It we are connected already, the next thing gdb will do is ask
271 // whether the launch succeeded, and if not, whether there is an
272 // error code. So we need to fetch one packet from gdb before we wait
273 // on the stop from the target.
275 uint32_t event_mask
= RNBContext::event_read_packet_available
;
276 nub_event_t set_events
= ctx
.Events().WaitForSetEvents(event_mask
);
278 if (set_events
& RNBContext::event_read_packet_available
) {
279 rnb_err_t err
= rnb_err
;
280 RNBRemote::PacketEnum type
;
282 err
= remote
->HandleReceivedPacket(&type
);
284 if (err
!= rnb_success
) {
285 DNBLogThreadedIf(LOG_RNB_MINIMAL
, "%s Error getting packet.",
287 return eRNBRunLoopModeExit
;
289 if (type
!= RNBRemote::query_launch_success
) {
290 DNBLogThreadedIf(LOG_RNB_MINIMAL
,
291 "%s Didn't get the expected qLaunchSuccess packet.",
297 while (pid
!= INVALID_NUB_PROCESS
) {
298 // Wait for process to start up and hit entry point
299 DNBLogThreadedIf(LOG_RNB_EVENTS
, "%s DNBProcessWaitForEvent (%4.4x, "
300 "eEventProcessRunningStateChanged | "
301 "eEventProcessStoppedStateChanged, true, "
304 nub_event_t set_events
=
305 DNBProcessWaitForEvents(pid
, eEventProcessRunningStateChanged
|
306 eEventProcessStoppedStateChanged
,
308 DNBLogThreadedIf(LOG_RNB_EVENTS
, "%s DNBProcessWaitForEvent (%4.4x, "
309 "eEventProcessRunningStateChanged | "
310 "eEventProcessStoppedStateChanged, true, "
311 "INFINITE) => 0x%8.8x",
312 __FUNCTION__
, pid
, set_events
);
314 if (set_events
== 0) {
315 pid
= INVALID_NUB_PROCESS
;
318 if (set_events
& (eEventProcessRunningStateChanged
|
319 eEventProcessStoppedStateChanged
)) {
320 nub_state_t pid_state
= DNBProcessGetState(pid
);
323 "%s process %4.4x state changed (eEventProcessStateChanged): %s",
324 __FUNCTION__
, pid
, DNBStateAsString(pid_state
));
329 case eStateAttaching
:
330 case eStateLaunching
:
331 case eStateSuspended
:
336 // Still waiting to stop at entry point...
341 ctx
.SetProcessID(pid
);
342 return eRNBRunLoopModeInferiorExecuting
;
346 pid
= INVALID_NUB_PROCESS
;
348 return eRNBRunLoopModeExit
;
352 DNBProcessResetEvents(pid
, set_events
);
356 return eRNBRunLoopModeExit
;
359 // This run loop mode will wait for the process to launch and hit its
360 // entry point. It will currently ignore all events except for the
361 // process state changed event, where it watches for the process stopped
362 // or crash process state.
363 RNBRunLoopMode
RNBRunLoopLaunchAttaching(RNBRemote
*remote
,
364 nub_process_t attach_pid
,
365 nub_process_t
&pid
) {
366 RNBContext
&ctx
= remote
->Context();
368 DNBLogThreadedIf(LOG_RNB_MINIMAL
, "%s Attaching to pid %i...", __FUNCTION__
,
371 pid
= DNBProcessAttach(attach_pid
, NULL
, ctx
.GetIgnoredExceptions(), err_str
,
375 if (pid
== INVALID_NUB_PROCESS
) {
376 ctx
.LaunchStatus().SetError(-1, DNBError::Generic
);
378 ctx
.LaunchStatus().SetErrorString(err_str
);
379 return eRNBRunLoopModeExit
;
381 ctx
.SetProcessID(pid
);
382 return eRNBRunLoopModeInferiorExecuting
;
386 // Watch for signals:
387 // SIGINT: so we can halt our inferior. (disabled for now)
388 // SIGPIPE: in case our child process dies
389 int g_sigint_received
= 0;
390 int g_sigpipe_received
= 0;
391 void signal_handler(int signo
) {
392 DNBLogThreadedIf(LOG_RNB_MINIMAL
, "%s (%s)", __FUNCTION__
,
393 SysSignal::Name(signo
));
398 if (g_pid
!= INVALID_NUB_PROCESS
) {
399 // Only send a SIGINT once...
400 if (g_sigint_received
== 1) {
401 switch (DNBProcessGetState(g_pid
)) {
404 DNBProcessSignal(g_pid
, SIGSTOP
);
415 g_sigpipe_received
= 1;
420 // Return the new run loop mode based off of the current process state
421 RNBRunLoopMode
HandleProcessStateChange(RNBRemote
*remote
, bool initialize
) {
422 RNBContext
&ctx
= remote
->Context();
423 nub_process_t pid
= ctx
.ProcessID();
425 if (pid
== INVALID_NUB_PROCESS
) {
426 DNBLogThreadedIf(LOG_RNB_MINIMAL
, "#### %s error: pid invalid, exiting...",
428 return eRNBRunLoopModeExit
;
430 nub_state_t pid_state
= DNBProcessGetState(pid
);
432 DNBLogThreadedIf(LOG_RNB_MINIMAL
,
433 "%s (&remote, initialize=%i) pid_state = %s", __FUNCTION__
,
434 (int)initialize
, DNBStateAsString(pid_state
));
439 // Something bad happened
440 return eRNBRunLoopModeExit
;
443 case eStateAttaching
:
444 case eStateLaunching
:
445 return eRNBRunLoopModeInferiorExecuting
;
447 case eStateSuspended
:
450 // If we stop due to a signal, so clear the fact that we got a SIGINT
451 // so we can stop ourselves again (but only while our inferior
452 // process is running..)
453 g_sigint_received
= 0;
454 if (initialize
== false) {
455 // Compare the last stop count to our current notion of a stop count
456 // to make sure we don't notify more than once for a given stop.
457 nub_size_t prev_pid_stop_count
= ctx
.GetProcessStopCount();
458 bool pid_stop_count_changed
=
459 ctx
.SetProcessStopCount(DNBProcessGetStopCount(pid
));
460 if (pid_stop_count_changed
) {
461 remote
->FlushSTDIO();
463 if (ctx
.GetProcessStopCount() == 1) {
465 LOG_RNB_MINIMAL
, "%s (&remote, initialize=%i) pid_state = %s "
466 "pid_stop_count %llu (old %llu)) Notify??? no, "
468 __FUNCTION__
, (int)initialize
, DNBStateAsString(pid_state
),
469 (uint64_t)ctx
.GetProcessStopCount(),
470 (uint64_t)prev_pid_stop_count
);
473 DNBLogThreadedIf(LOG_RNB_MINIMAL
, "%s (&remote, initialize=%i) "
474 "pid_state = %s pid_stop_count "
475 "%llu (old %llu)) Notify??? YES!!!",
476 __FUNCTION__
, (int)initialize
,
477 DNBStateAsString(pid_state
),
478 (uint64_t)ctx
.GetProcessStopCount(),
479 (uint64_t)prev_pid_stop_count
);
480 remote
->NotifyThatProcessStopped();
484 LOG_RNB_MINIMAL
, "%s (&remote, initialize=%i) pid_state = %s "
485 "pid_stop_count %llu (old %llu)) Notify??? "
487 __FUNCTION__
, (int)initialize
, DNBStateAsString(pid_state
),
488 (uint64_t)ctx
.GetProcessStopCount(), (uint64_t)prev_pid_stop_count
);
491 return eRNBRunLoopModeInferiorExecuting
;
495 return eRNBRunLoopModeInferiorExecuting
;
498 remote
->HandlePacket_last_signal(NULL
);
499 return eRNBRunLoopModeExit
;
501 return eRNBRunLoopModeExit
;
505 return eRNBRunLoopModeExit
;
508 // This function handles the case where our inferior program is stopped and
509 // we are waiting for gdb remote protocol packets. When a packet occurs that
510 // makes the inferior run, we need to leave this function with a new state
511 // as the return code.
512 RNBRunLoopMode
RNBRunLoopInferiorExecuting(RNBRemote
*remote
) {
513 DNBLogThreadedIf(LOG_RNB_MINIMAL
, "#### %s", __FUNCTION__
);
514 RNBContext
&ctx
= remote
->Context();
516 // Init our mode and set 'is_running' based on the current process state
517 RNBRunLoopMode mode
= HandleProcessStateChange(remote
, true);
519 while (ctx
.ProcessID() != INVALID_NUB_PROCESS
) {
521 std::string set_events_str
;
522 uint32_t event_mask
= ctx
.NormalEventBits();
524 if (!ctx
.ProcessStateRunning()) {
525 // Clear some bits if we are not running so we don't send any async
527 event_mask
&= ~RNBContext::event_proc_stdio_available
;
528 event_mask
&= ~RNBContext::event_proc_profile_data
;
531 // We want to make sure we consume all process state changes and have
532 // whomever is notifying us to wait for us to reset the event bit before
534 // ctx.Events().SetResetAckMask (RNBContext::event_proc_state_changed);
536 DNBLogThreadedIf(LOG_RNB_EVENTS
,
537 "%s ctx.Events().WaitForSetEvents(0x%08x) ...",
538 __FUNCTION__
, event_mask
);
539 nub_event_t set_events
= ctx
.Events().WaitForSetEvents(event_mask
);
540 DNBLogThreadedIf(LOG_RNB_EVENTS
,
541 "%s ctx.Events().WaitForSetEvents(0x%08x) => 0x%08x (%s)",
542 __FUNCTION__
, event_mask
, set_events
,
543 ctx
.EventsAsString(set_events
, set_events_str
));
546 if ((set_events
& RNBContext::event_proc_thread_exiting
) ||
547 (set_events
& RNBContext::event_proc_stdio_available
)) {
548 remote
->FlushSTDIO();
551 if (set_events
& RNBContext::event_proc_profile_data
) {
552 remote
->SendAsyncProfileData();
555 if (set_events
& RNBContext::event_read_packet_available
) {
556 // handleReceivedPacket will take care of resetting the
557 // event_read_packet_available events when there are no more...
558 set_events
^= RNBContext::event_read_packet_available
;
560 if (ctx
.ProcessStateRunning()) {
561 if (remote
->HandleAsyncPacket() == rnb_not_connected
) {
562 // TODO: connect again? Exit?
565 if (remote
->HandleReceivedPacket() == rnb_not_connected
) {
566 // TODO: connect again? Exit?
571 if (set_events
& RNBContext::event_proc_state_changed
) {
572 mode
= HandleProcessStateChange(remote
, false);
573 ctx
.Events().ResetEvents(RNBContext::event_proc_state_changed
);
574 set_events
^= RNBContext::event_proc_state_changed
;
577 if (set_events
& RNBContext::event_proc_thread_exiting
) {
578 DNBLog("debugserver's process monitoring thread has exited.");
579 mode
= eRNBRunLoopModeExit
;
582 if (set_events
& RNBContext::event_read_thread_exiting
) {
583 // Out remote packet receiving thread exited, exit for now.
585 "debugserver's packet communication to lldb has been shut down.");
586 if (ctx
.HasValidProcessID()) {
587 nub_process_t pid
= ctx
.ProcessID();
588 // TODO: We should add code that will leave the current process
589 // in its current state and listen for another connection...
590 if (ctx
.ProcessStateRunning()) {
591 if (ctx
.GetDetachOnError()) {
592 DNBLog("debugserver has a valid PID %d, it is still running. "
593 "detaching from the inferior process.",
595 DNBProcessDetach(pid
);
597 DNBLog("debugserver killing the inferior process, pid %d.", pid
);
601 if (ctx
.GetDetachOnError()) {
602 DNBLog("debugserver has a valid PID %d but it may no longer "
603 "be running, detaching from the inferior process.",
605 DNBProcessDetach(pid
);
609 mode
= eRNBRunLoopModeExit
;
613 // Reset all event bits that weren't reset for now...
615 ctx
.Events().ResetEvents(set_events
);
617 if (mode
!= eRNBRunLoopModeInferiorExecuting
)
624 RNBRunLoopMode
RNBRunLoopPlatform(RNBRemote
*remote
) {
625 RNBRunLoopMode mode
= eRNBRunLoopModePlatformMode
;
626 RNBContext
&ctx
= remote
->Context();
628 while (mode
== eRNBRunLoopModePlatformMode
) {
629 std::string set_events_str
;
630 const uint32_t event_mask
= RNBContext::event_read_packet_available
|
631 RNBContext::event_read_thread_exiting
;
633 DNBLogThreadedIf(LOG_RNB_EVENTS
,
634 "%s ctx.Events().WaitForSetEvents(0x%08x) ...",
635 __FUNCTION__
, event_mask
);
636 nub_event_t set_events
= ctx
.Events().WaitForSetEvents(event_mask
);
637 DNBLogThreadedIf(LOG_RNB_EVENTS
,
638 "%s ctx.Events().WaitForSetEvents(0x%08x) => 0x%08x (%s)",
639 __FUNCTION__
, event_mask
, set_events
,
640 ctx
.EventsAsString(set_events
, set_events_str
));
643 if (set_events
& RNBContext::event_read_packet_available
) {
644 if (remote
->HandleReceivedPacket() == rnb_not_connected
)
645 mode
= eRNBRunLoopModeExit
;
648 if (set_events
& RNBContext::event_read_thread_exiting
) {
649 mode
= eRNBRunLoopModeExit
;
651 ctx
.Events().ResetEvents(set_events
);
654 return eRNBRunLoopModeExit
;
657 // Convenience function to set up the remote listening port
658 // Returns 1 for success 0 for failure.
660 static void PortWasBoundCallbackUnixSocket(const void *baton
, in_port_t port
) {
661 //::printf ("PortWasBoundCallbackUnixSocket (baton = %p, port = %u)\n", baton,
664 const char *unix_socket_name
= (const char *)baton
;
666 if (unix_socket_name
&& unix_socket_name
[0]) {
667 // We were given a unix socket name to use to communicate the port
668 // that we ended up binding to back to our parent process
669 struct sockaddr_un saddr_un
;
670 int s
= ::socket(AF_UNIX
, SOCK_STREAM
, 0);
672 perror("error: socket (AF_UNIX, SOCK_STREAM, 0)");
676 saddr_un
.sun_family
= AF_UNIX
;
677 ::strlcpy(saddr_un
.sun_path
, unix_socket_name
,
678 sizeof(saddr_un
.sun_path
) - 1);
679 saddr_un
.sun_path
[sizeof(saddr_un
.sun_path
) - 1] = '\0';
680 saddr_un
.sun_len
= SUN_LEN(&saddr_un
);
682 if (::connect(s
, (struct sockaddr
*)&saddr_un
,
683 static_cast<socklen_t
>(SUN_LEN(&saddr_un
))) < 0) {
684 perror("error: connect (socket, &saddr_un, saddr_un_len)");
688 //::printf ("connect () sucess!!\n");
690 // We were able to connect to the socket, now write our PID so whomever
691 // launched us will know this process's ID
692 RNBLogSTDOUT("Listening to port %i...\n", port
);
695 const int pid_str_len
= ::snprintf(pid_str
, sizeof(pid_str
), "%u", port
);
696 const ssize_t bytes_sent
= ::send(s
, pid_str
, pid_str_len
, 0);
698 if (pid_str_len
!= bytes_sent
) {
699 perror("error: send (s, pid_str, pid_str_len, 0)");
703 //::printf ("send () sucess!!\n");
705 // We are done with the socket
710 static void PortWasBoundCallbackNamedPipe(const void *baton
, uint16_t port
) {
711 const char *named_pipe
= (const char *)baton
;
712 if (named_pipe
&& named_pipe
[0]) {
713 int fd
= ::open(named_pipe
, O_WRONLY
);
716 const ssize_t port_str_len
=
717 ::snprintf(port_str
, sizeof(port_str
), "%u", port
);
718 // Write the port number as a C string with the NULL terminator
719 ::write(fd
, port_str
, port_str_len
+ 1);
725 static int ConnectRemote(RNBRemote
*remote
, const char *host
, int port
,
726 bool reverse_connect
, const char *named_pipe_path
,
727 const char *unix_socket_name
) {
728 if (!remote
->Comm().IsConnected()) {
729 if (reverse_connect
) {
732 "error: invalid port supplied for reverse connection: %i.\n", port
);
735 if (remote
->Comm().Connect(host
, port
) != rnb_success
) {
736 DNBLogThreaded("Failed to reverse connect to %s:%i.\n", host
, port
);
741 RNBLogSTDOUT("Listening to port %i for a connection from %s...\n", port
,
742 host
? host
: "127.0.0.1");
743 if (unix_socket_name
&& unix_socket_name
[0]) {
744 if (remote
->Comm().Listen(host
, port
, PortWasBoundCallbackUnixSocket
,
745 unix_socket_name
) != rnb_success
) {
746 RNBLogSTDERR("Failed to get connection from a remote gdb process.\n");
750 if (remote
->Comm().Listen(host
, port
, PortWasBoundCallbackNamedPipe
,
751 named_pipe_path
) != rnb_success
) {
752 RNBLogSTDERR("Failed to get connection from a remote gdb process.\n");
757 remote
->StartReadRemoteDataThread();
762 // FILE based Logging callback that can be registered with
763 // DNBLogSetLogCallback
764 void FileLogCallback(void *baton
, uint32_t flags
, const char *format
,
766 if (baton
== NULL
|| format
== NULL
)
769 ::vfprintf((FILE *)baton
, format
, args
);
770 ::fprintf((FILE *)baton
, "\n");
771 ::fflush((FILE *)baton
);
774 void show_version_and_exit(int exit_code
) {
775 const char *in_translation
= "";
776 if (DNBDebugserverIsTranslated())
777 in_translation
= " (running under translation)";
778 printf("%s-%s for %s%s.\n", DEBUGSERVER_PROGRAM_NAME
, DEBUGSERVER_VERSION_STR
,
779 RNB_ARCH
, in_translation
);
783 void show_usage_and_exit(int exit_code
) {
785 "Usage:\n %s host:port [program-name program-arg1 program-arg2 ...]\n",
786 DEBUGSERVER_PROGRAM_NAME
);
787 RNBLogSTDERR(" %s /path/file [program-name program-arg1 program-arg2 ...]\n",
788 DEBUGSERVER_PROGRAM_NAME
);
789 RNBLogSTDERR(" %s host:port --attach=<pid>\n", DEBUGSERVER_PROGRAM_NAME
);
790 RNBLogSTDERR(" %s /path/file --attach=<pid>\n", DEBUGSERVER_PROGRAM_NAME
);
791 RNBLogSTDERR(" %s host:port --attach=<process_name>\n",
792 DEBUGSERVER_PROGRAM_NAME
);
793 RNBLogSTDERR(" %s /path/file --attach=<process_name>\n",
794 DEBUGSERVER_PROGRAM_NAME
);
798 // option descriptors for getopt_long_only()
799 static struct option g_long_options
[] = {
800 {"attach", required_argument
, NULL
, 'a'},
801 {"arch", required_argument
, NULL
, 'A'},
802 {"debug", no_argument
, NULL
, 'g'},
803 {"kill-on-error", no_argument
, NULL
, 'K'},
804 {"verbose", no_argument
, NULL
, 'v'},
805 {"version", no_argument
, NULL
, 'V'},
806 {"lockdown", no_argument
, &g_lockdown_opt
, 1}, // short option "-k"
807 {"applist", no_argument
, &g_applist_opt
, 1}, // short option "-t"
808 {"log-file", required_argument
, NULL
, 'l'},
809 {"log-flags", required_argument
, NULL
, 'f'},
810 {"launch", required_argument
, NULL
, 'x'}, // Valid values are "auto",
811 // "posix-spawn", "fork-exec",
812 // "springboard" (arm only)
813 {"waitfor", required_argument
, NULL
,
814 'w'}, // Wait for a process whose name starts with ARG
815 {"waitfor-interval", required_argument
, NULL
,
816 'i'}, // Time in usecs to wait between sampling the pid list when waiting
817 // for a process by name
818 {"waitfor-duration", required_argument
, NULL
,
819 'd'}, // The time in seconds to wait for a process to show up by name
820 {"native-regs", no_argument
, NULL
, 'r'}, // Specify to use the native
821 // registers instead of the gdb
822 // defaults for the architecture.
823 {"stdio-path", required_argument
, NULL
,
824 's'}, // Set the STDIO path to be used when launching applications (STDIN,
825 // STDOUT and STDERR) (only if debugserver launches the process)
826 {"stdin-path", required_argument
, NULL
,
827 'I'}, // Set the STDIN path to be used when launching applications (only if
828 // debugserver launches the process)
829 {"stdout-path", required_argument
, NULL
,
830 'O'}, // Set the STDOUT path to be used when launching applications (only
831 // if debugserver launches the process)
832 {"stderr-path", required_argument
, NULL
,
833 'E'}, // Set the STDERR path to be used when launching applications (only
834 // if debugserver launches the process)
835 {"no-stdio", no_argument
, NULL
,
836 'n'}, // Do not set up any stdio (perhaps the program is a GUI program)
837 // (only if debugserver launches the process)
838 {"setsid", no_argument
, NULL
,
839 'S'}, // call setsid() to make debugserver run in its own session
840 {"disable-aslr", no_argument
, NULL
, 'D'}, // Use _POSIX_SPAWN_DISABLE_ASLR
841 // to avoid shared library
843 {"working-dir", required_argument
, NULL
,
844 'W'}, // The working directory that the inferior process should have (only
845 // if debugserver launches the process)
846 {"platform", required_argument
, NULL
,
847 'p'}, // Put this executable into a remote platform mode
848 {"unix-socket", required_argument
, NULL
,
849 'u'}, // If we need to handshake with our parent process, an option will be
850 // passed down that specifies a unix socket name to use
851 {"fd", required_argument
, NULL
,
852 '2'}, // A file descriptor was passed to this process when spawned that
853 // is already open and ready for communication
854 {"named-pipe", required_argument
, NULL
, 'P'},
855 {"reverse-connect", no_argument
, NULL
, 'R'},
856 {"env", required_argument
, NULL
,
857 'e'}, // When debugserver launches the process, set a single environment
858 // entry as specified by the option value ("./debugserver -e FOO=1 -e
859 // BAR=2 localhost:1234 -- /bin/ls")
860 {"forward-env", no_argument
, NULL
,
861 'F'}, // When debugserver launches the process, forward debugserver's
862 // current environment variables to the child process ("./debugserver
863 // -F localhost:1234 -- /bin/ls"
864 {"unmask-signals", no_argument
, NULL
,
865 'U'}, // debugserver will ignore EXC_MASK_BAD_ACCESS,
866 // EXC_MASK_BAD_INSTRUCTION and EXC_MASK_ARITHMETIC, which results in
867 // SIGSEGV, SIGILL and SIGFPE being propagated to the target process.
870 int communication_fd
= -1;
873 int main(int argc
, char *argv
[]) {
874 // If debugserver is launched with DYLD_INSERT_LIBRARIES, unset it so we
875 // don't spawn child processes with this enabled.
876 unsetenv("DYLD_INSERT_LIBRARIES");
878 const char *argv_sub_zero
=
879 argv
[0]; // save a copy of argv[0] for error reporting post-launch
881 #if defined(__APPLE__)
882 pthread_setname_np("main thread");
883 #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
884 struct sched_param thread_param
;
885 int thread_sched_policy
;
886 if (pthread_getschedparam(pthread_self(), &thread_sched_policy
,
887 &thread_param
) == 0) {
888 thread_param
.sched_priority
= 47;
889 pthread_setschedparam(pthread_self(), thread_sched_policy
, &thread_param
);
892 ::proc_set_wakemon_params(
894 0); // Allow up to 500 wakeups/sec to avoid EXC_RESOURCE for normal use.
898 g_isatty
= ::isatty(STDIN_FILENO
);
900 // ::printf ("uid=%u euid=%u gid=%u egid=%u\n",
906 // signal (SIGINT, signal_handler);
907 signal(SIGPIPE
, signal_handler
);
908 signal(SIGHUP
, signal_handler
);
910 // We're always sitting in waitpid or kevent waiting on our target process'
912 // we don't need no stinking SIGCHLD's...
915 sigemptyset(&sigset
);
916 sigaddset(&sigset
, SIGCHLD
);
917 sigprocmask(SIG_BLOCK
, &sigset
, NULL
);
919 // Set up DNB logging by default. If the user passes different log flags or a
920 // log file, these settings will be modified after processing the command line
922 if (auto log_callback
= OsLogger::GetLogFunction())
923 DNBLogSetLogCallback(log_callback
, nullptr);
924 DNBLogSetLogMask(/*log_flags*/ 0);
926 g_remoteSP
= std::make_shared
<RNBRemote
>();
928 RNBRemote
*remote
= g_remoteSP
.get();
929 if (remote
== NULL
) {
930 RNBLogSTDERR("error: failed to create a remote connection class\n");
934 RNBContext
&ctx
= remote
->Context();
937 int attach_pid
= INVALID_NUB_PROCESS
;
939 FILE *log_file
= NULL
;
940 uint32_t log_flags
= 0;
943 int long_option_index
= 0;
945 std::string compile_options
;
946 std::string waitfor_pid_name
; // Wait for a process that starts with this name
947 std::string attach_pid_name
;
948 std::string arch_name
;
949 std::string working_dir
; // The new working directory to use for the inferior
950 std::string unix_socket_name
; // If we need to handshake with our parent
951 // process, an option will be passed down that
952 // specifies a unix socket name to use
953 std::string named_pipe_path
; // If we need to handshake with our parent
954 // process, an option will be passed down that
955 // specifies a named pipe to use
956 useconds_t waitfor_interval
= 1000; // Time in usecs between process lists
957 // polls when waiting for a process by
958 // name, default 1 msec.
959 useconds_t waitfor_duration
=
960 0; // Time in seconds to wait for a process by name, 0 means wait forever.
961 bool no_stdio
= false;
962 bool reverse_connect
= false; // Set to true by an option to indicate we
963 // should reverse connect to the host:port
964 // supplied as the first debugserver argument
966 #if !defined(DNBLOG_ENABLED)
967 compile_options
+= "(no-logging) ";
970 RNBRunLoopMode start_mode
= eRNBRunLoopModeExit
;
972 char short_options
[512];
973 uint32_t short_options_idx
= 0;
975 // Handle the two case that don't have short options in g_long_options
976 short_options
[short_options_idx
++] = 'k';
977 short_options
[short_options_idx
++] = 't';
979 for (i
= 0; g_long_options
[i
].name
!= NULL
; ++i
) {
980 if (isalpha(g_long_options
[i
].val
)) {
981 short_options
[short_options_idx
++] = g_long_options
[i
].val
;
982 switch (g_long_options
[i
].has_arg
) {
987 case optional_argument
:
988 short_options
[short_options_idx
++] = ':';
989 short_options
[short_options_idx
++] = ':';
991 case required_argument
:
992 short_options
[short_options_idx
++] = ':';
997 // NULL terminate the short option string.
998 short_options
[short_options_idx
++] = '\0';
1007 bool forward_env
= false;
1008 while ((ch
= getopt_long_only(argc
, argv
, short_options
, g_long_options
,
1009 &long_option_index
)) != -1) {
1010 DNBLogDebug("option: ch == %c (0x%2.2x) --%s%c%s\n", ch
, (uint8_t)ch
,
1011 g_long_options
[long_option_index
].name
,
1012 g_long_options
[long_option_index
].has_arg
? '=' : ' ',
1013 optarg
? optarg
: "");
1015 case 0: // Any optional that auto set themselves will return 0
1019 if (optarg
&& optarg
[0])
1020 arch_name
.assign(optarg
);
1024 if (optarg
&& optarg
[0]) {
1025 if (isdigit(optarg
[0])) {
1027 attach_pid
= static_cast<int>(strtoul(optarg
, &end
, 0));
1028 if (end
== NULL
|| *end
!= '\0') {
1029 RNBLogSTDERR("error: invalid pid option '%s'\n", optarg
);
1033 attach_pid_name
= optarg
;
1035 start_mode
= eRNBRunLoopModeInferiorAttaching
;
1041 if (optarg
&& optarg
[0]) {
1042 waitfor_pid_name
= optarg
;
1043 start_mode
= eRNBRunLoopModeInferiorAttaching
;
1047 // --waitfor-interval=USEC
1049 if (optarg
&& optarg
[0]) {
1051 waitfor_interval
= static_cast<useconds_t
>(strtoul(optarg
, &end
, 0));
1052 if (end
== NULL
|| *end
!= '\0') {
1053 RNBLogSTDERR("error: invalid waitfor-interval option value '%s'.\n",
1060 // --waitfor-duration=SEC
1062 if (optarg
&& optarg
[0]) {
1064 waitfor_duration
= static_cast<useconds_t
>(strtoul(optarg
, &end
, 0));
1065 if (end
== NULL
|| *end
!= '\0') {
1066 RNBLogSTDERR("error: invalid waitfor-duration option value '%s'.\n",
1074 g_detach_on_error
= false;
1077 if (optarg
&& optarg
[0])
1078 working_dir
.assign(optarg
);
1082 if (optarg
&& optarg
[0]) {
1083 if (strcasecmp(optarg
, "auto") == 0)
1084 g_launch_flavor
= eLaunchFlavorDefault
;
1085 else if (strcasestr(optarg
, "posix") == optarg
) {
1087 "[LaunchAttach] launch flavor is posix_spawn via cmdline option");
1088 g_launch_flavor
= eLaunchFlavorPosixSpawn
;
1089 } else if (strcasestr(optarg
, "fork") == optarg
)
1090 g_launch_flavor
= eLaunchFlavorForkExec
;
1091 #ifdef WITH_SPRINGBOARD
1092 else if (strcasestr(optarg
, "spring") == optarg
) {
1094 "[LaunchAttach] launch flavor is SpringBoard via cmdline option");
1095 g_launch_flavor
= eLaunchFlavorSpringBoard
;
1099 else if (strcasestr(optarg
, "backboard") == optarg
) {
1100 DNBLog("[LaunchAttach] launch flavor is BKS via cmdline option");
1101 g_launch_flavor
= eLaunchFlavorBKS
;
1105 else if (strcasestr(optarg
, "frontboard") == optarg
) {
1106 DNBLog("[LaunchAttach] launch flavor is FBS via cmdline option");
1107 g_launch_flavor
= eLaunchFlavorFBS
;
1112 RNBLogSTDERR("error: invalid TYPE for the --launch=TYPE (-x TYPE) "
1115 RNBLogSTDERR("Valid values TYPE are:\n");
1117 " auto Auto-detect the best launch method to use.\n");
1119 " posix Launch the executable using posix_spawn.\n");
1121 " fork Launch the executable using fork and exec.\n");
1122 #ifdef WITH_SPRINGBOARD
1124 " spring Launch the executable through Springboard.\n");
1127 RNBLogSTDERR(" backboard Launch the executable through BackBoard "
1131 RNBLogSTDERR(" frontboard Launch the executable through FrontBoard "
1139 case 'l': // Set Log File
1140 if (optarg
&& optarg
[0]) {
1141 if (strcasecmp(optarg
, "stdout") == 0)
1143 else if (strcasecmp(optarg
, "stderr") == 0)
1146 log_file
= fopen(optarg
, "w");
1147 if (log_file
!= NULL
)
1148 setlinebuf(log_file
);
1151 if (log_file
== NULL
) {
1152 const char *errno_str
= strerror(errno
);
1154 "Failed to open log file '%s' for writing: errno = %i (%s)",
1155 optarg
, errno
, errno_str
? errno_str
: "unknown error");
1160 case 'f': // Log Flags
1161 if (optarg
&& optarg
[0])
1162 log_flags
= static_cast<uint32_t>(strtoul(optarg
, NULL
, 0));
1167 DNBLogSetDebug(debug
);
1179 // Do nothing, native regs is the default these days
1183 reverse_connect
= true;
1186 DNBLogSetVerbose(1);
1190 show_version_and_exit(0);
1194 ctx
.GetSTDIN().assign(optarg
);
1195 ctx
.GetSTDOUT().assign(optarg
);
1196 ctx
.GetSTDERR().assign(optarg
);
1200 ctx
.GetSTDIN().assign(optarg
);
1204 ctx
.GetSTDOUT().assign(optarg
);
1208 ctx
.GetSTDERR().assign(optarg
);
1216 // Put debugserver into a new session. Terminals group processes
1217 // into sessions and when a special terminal key sequences
1218 // (like control+c) are typed they can cause signals to go out to
1219 // all processes in a session. Using this --setsid (-S) option
1220 // will cause debugserver to run in its own sessions and be free
1221 // from such issues.
1223 // This is useful when debugserver is spawned from a command
1224 // line application that uses debugserver to do the debugging,
1225 // yet that application doesn't want debugserver receiving the
1226 // signals sent to the session (i.e. dying when anyone hits ^C).
1234 start_mode
= eRNBRunLoopModePlatformMode
;
1238 unix_socket_name
.assign(optarg
);
1242 named_pipe_path
.assign(optarg
);
1246 // Pass a single specified environment variable down to the process that
1248 remote
->Context().PushEnvironment(optarg
);
1256 ctx
.AddDefaultIgnoredExceptions();
1260 // File descriptor passed to this process during fork/exec and is already
1261 // open and ready for communication.
1262 communication_fd
= atoi(optarg
);
1267 if (arch_name
.empty()) {
1268 #if defined(__arm__)
1269 arch_name
.assign("arm");
1272 DNBSetArchitecture(arch_name
.c_str());
1275 // if (arch_name.empty())
1277 // fprintf(stderr, "error: no architecture was specified\n");
1280 // Skip any options we consumed with getopt_long_only
1284 if (!working_dir
.empty()) {
1285 if (remote
->Context().SetWorkingDirectory(working_dir
.c_str()) == false) {
1286 RNBLogSTDERR("error: working directory doesn't exist '%s'.\n",
1287 working_dir
.c_str());
1292 remote
->Context().SetDetachOnError(g_detach_on_error
);
1294 remote
->Initialize();
1296 // It is ok for us to set NULL as the logfile (this will disable any logging)
1298 if (log_file
!= NULL
) {
1299 DNBLog("debugserver is switching to logging to a file.");
1300 DNBLogSetLogCallback(FileLogCallback
, log_file
);
1301 // If our log file was set, yet we have no log flags, log everything!
1303 log_flags
= LOG_ALL
| LOG_RNB_ALL
;
1305 DNBLogSetLogMask(log_flags
);
1307 if (DNBLogEnabled()) {
1308 for (i
= 0; i
< argc
; i
++)
1309 DNBLogDebug("argv[%i] = %s", i
, argv
[i
]);
1312 // as long as we're dropping remotenub in as a replacement for gdbserver,
1313 // explicitly note that this is not gdbserver.
1315 const char *in_translation
= "";
1316 if (DNBDebugserverIsTranslated())
1317 in_translation
= " (running under translation)";
1318 RNBLogSTDOUT("%s-%s %sfor %s%s.\n", DEBUGSERVER_PROGRAM_NAME
,
1319 DEBUGSERVER_VERSION_STR
, compile_options
.c_str(), RNB_ARCH
,
1323 int port
= INT32_MAX
;
1327 if (g_lockdown_opt
== 0 && g_applist_opt
== 0 && communication_fd
== -1) {
1328 // Make sure we at least have port
1330 show_usage_and_exit(1);
1332 // accept 'localhost:' prefix on port number
1333 std::string host_specifier
= argv
[0];
1334 auto colon_location
= host_specifier
.rfind(':');
1335 if (colon_location
!= std::string::npos
) {
1336 host
= host_specifier
.substr(0, colon_location
);
1337 std::string port_str
=
1338 host_specifier
.substr(colon_location
+ 1, std::string::npos
);
1340 port
= strtoul(port_str
.c_str(), &end_ptr
, 0);
1341 if (end_ptr
< port_str
.c_str() + port_str
.size())
1342 show_usage_and_exit(2);
1343 if (host
.front() == '[' && host
.back() == ']')
1344 host
= host
.substr(1, host
.size() - 2);
1345 DNBLogDebug("host = '%s' port = %i", host
.c_str(), port
);
1347 // No hostname means "localhost"
1348 int items_scanned
= ::sscanf(argv
[0], "%i", &port
);
1349 if (items_scanned
== 1) {
1351 DNBLogDebug("host = '%s' port = %i", host
.c_str(), port
);
1352 } else if (argv
[0][0] == '/') {
1354 strlcpy(str
, argv
[0], sizeof(str
));
1356 show_usage_and_exit(2);
1360 // We just used the 'host:port' or the '/path/file' arg...
1365 // If we know we're waiting to attach, we don't need any of this other info.
1366 if (start_mode
!= eRNBRunLoopModeInferiorAttaching
&&
1367 start_mode
!= eRNBRunLoopModePlatformMode
) {
1368 if (argc
== 0 || g_lockdown_opt
) {
1369 if (g_lockdown_opt
!= 0) {
1370 // Work around for SIGPIPE crashes due to posix_spawn issue.
1371 // We have to close STDOUT and STDERR, else the first time we
1372 // try and do any, we get SIGPIPE and die as posix_spawn is
1373 // doing bad things with our file descriptors at the moment.
1374 int null
= open("/dev/null", O_RDWR
);
1375 dup2(null
, STDOUT_FILENO
);
1376 dup2(null
, STDERR_FILENO
);
1377 } else if (g_applist_opt
!= 0) {
1378 DNBLog("debugserver running in --applist mode");
1379 // List all applications we are able to see
1380 std::string applist_plist
;
1381 int err
= ListApplications(applist_plist
, false, false);
1383 fputs(applist_plist
.c_str(), stdout
);
1385 RNBLogSTDERR("error: ListApplications returned error %i\n", err
);
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
1393 DNBLogDebug("Get args from remote protocol...");
1394 start_mode
= eRNBRunLoopModeGetStartModeFromRemoteProtocol
;
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
]);
1406 if (start_mode
== eRNBRunLoopModeExit
)
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
1414 char **host_env
= *_NSGetEnviron();
1417 for (i
= 0; (env_entry
= host_env
[i
]) != NULL
; ++i
)
1418 remote
->Context().PushEnvironmentIfNeeded(env_entry
);
1421 RNBRunLoopMode mode
= start_mode
;
1422 char err_str
[1024] = {'\0'};
1424 while (mode
!= eRNBRunLoopModeExit
) {
1426 case eRNBRunLoopModeGetStartModeFromRemoteProtocol
:
1427 #ifdef WITH_LOCKDOWN
1428 if (g_lockdown_opt
) {
1429 if (!remote
->Comm().IsConnected()) {
1430 if (remote
->Comm().ConnectToService() != rnb_success
) {
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 DNBLog("debugserver running in applist mode under lockdown");
1437 std::string applist_plist
;
1438 if (ListApplications(applist_plist
, false, false) == 0) {
1439 DNBLogDebug("Task list: %s", applist_plist
.c_str());
1441 remote
->Comm().Write(applist_plist
.c_str(), applist_plist
.size());
1442 // Issue a read that will never yield any data until the other
1444 // closes the socket so this process doesn't just exit and cause
1446 // socket to close prematurely on the other end and cause data
1449 remote
->Comm().Read(buf
);
1451 remote
->Comm().Disconnect(false);
1452 mode
= eRNBRunLoopModeExit
;
1455 // Start watching for remote packets
1456 remote
->StartReadRemoteDataThread();
1461 if (port
!= INT32_MAX
) {
1462 if (!ConnectRemote(remote
, host
.c_str(), port
, reverse_connect
,
1463 named_pipe_path
.c_str(), unix_socket_name
.c_str()))
1464 mode
= eRNBRunLoopModeExit
;
1465 } else if (str
[0] == '/') {
1466 if (remote
->Comm().OpenFile(str
))
1467 mode
= eRNBRunLoopModeExit
;
1468 } else if (communication_fd
>= 0) {
1469 // We were passed a file descriptor to use during fork/exec that is
1471 // in our process, so lets just use it!
1472 if (remote
->Comm().useFD(communication_fd
))
1473 mode
= eRNBRunLoopModeExit
;
1475 remote
->StartReadRemoteDataThread();
1478 if (mode
!= eRNBRunLoopModeExit
) {
1479 RNBLogSTDOUT("Got a connection, waiting for process information for "
1480 "launching or attaching.\n");
1482 mode
= RNBRunLoopGetStartModeFromRemote(remote
);
1486 case eRNBRunLoopModeInferiorAttaching
:
1487 if (!waitfor_pid_name
.empty()) {
1488 // Set our end wait time if we are using a waitfor-duration
1489 // option that may have been specified
1490 struct timespec attach_timeout_abstime
, *timeout_ptr
= NULL
;
1491 if (waitfor_duration
!= 0) {
1492 DNBTimer::OffsetTimeOfDay(&attach_timeout_abstime
, waitfor_duration
,
1494 timeout_ptr
= &attach_timeout_abstime
;
1496 nub_launch_flavor_t launch_flavor
= g_launch_flavor
;
1497 if (launch_flavor
== eLaunchFlavorDefault
)
1498 launch_flavor
= default_launch_flavor(waitfor_pid_name
.c_str());
1500 ctx
.SetLaunchFlavor(launch_flavor
);
1501 bool ignore_existing
= false;
1502 RNBLogSTDOUT("Waiting to attach to process %s...\n",
1503 waitfor_pid_name
.c_str());
1504 nub_process_t pid
= DNBProcessAttachWait(
1505 &ctx
, waitfor_pid_name
.c_str(), ignore_existing
, timeout_ptr
,
1506 waitfor_interval
, err_str
, sizeof(err_str
));
1509 if (pid
== INVALID_NUB_PROCESS
) {
1510 ctx
.LaunchStatus().SetError(-1, DNBError::Generic
);
1512 ctx
.LaunchStatus().SetErrorString(err_str
);
1513 RNBLogSTDERR("error: failed to attach to process named: \"%s\" %s\n",
1514 waitfor_pid_name
.c_str(), err_str
);
1515 mode
= eRNBRunLoopModeExit
;
1517 ctx
.SetProcessID(pid
);
1518 mode
= eRNBRunLoopModeInferiorExecuting
;
1520 } else if (attach_pid
!= INVALID_NUB_PROCESS
) {
1522 RNBLogSTDOUT("Attaching to process %i...\n", attach_pid
);
1523 nub_process_t attached_pid
;
1524 mode
= RNBRunLoopLaunchAttaching(remote
, attach_pid
, attached_pid
);
1525 if (mode
!= eRNBRunLoopModeInferiorExecuting
) {
1526 const char *error_str
= remote
->Context().LaunchStatus().AsString();
1527 RNBLogSTDERR("error: failed to attach process %i: %s\n", attach_pid
,
1528 error_str
? error_str
: "unknown error.");
1529 mode
= eRNBRunLoopModeExit
;
1531 } else if (!attach_pid_name
.empty()) {
1532 struct timespec attach_timeout_abstime
, *timeout_ptr
= NULL
;
1533 if (waitfor_duration
!= 0) {
1534 DNBTimer::OffsetTimeOfDay(&attach_timeout_abstime
, waitfor_duration
,
1536 timeout_ptr
= &attach_timeout_abstime
;
1539 RNBLogSTDOUT("Attaching to process %s...\n", attach_pid_name
.c_str());
1540 nub_process_t pid
= DNBProcessAttachByName(
1541 attach_pid_name
.c_str(), timeout_ptr
, ctx
.GetIgnoredExceptions(),
1542 err_str
, sizeof(err_str
));
1544 if (pid
== INVALID_NUB_PROCESS
) {
1545 ctx
.LaunchStatus().SetError(-1, DNBError::Generic
);
1547 ctx
.LaunchStatus().SetErrorString(err_str
);
1548 RNBLogSTDERR("error: failed to attach to process named: \"%s\" %s\n",
1549 waitfor_pid_name
.c_str(), err_str
);
1550 mode
= eRNBRunLoopModeExit
;
1552 ctx
.SetProcessID(pid
);
1553 mode
= eRNBRunLoopModeInferiorExecuting
;
1558 "error: asked to attach with empty name and invalid PID.\n");
1559 mode
= eRNBRunLoopModeExit
;
1562 if (mode
!= eRNBRunLoopModeExit
) {
1563 if (port
!= INT32_MAX
) {
1564 if (!ConnectRemote(remote
, host
.c_str(), port
, reverse_connect
,
1565 named_pipe_path
.c_str(), unix_socket_name
.c_str()))
1566 mode
= eRNBRunLoopModeExit
;
1567 } else if (str
[0] == '/') {
1568 if (remote
->Comm().OpenFile(str
))
1569 mode
= eRNBRunLoopModeExit
;
1570 } else if (communication_fd
>= 0) {
1571 // We were passed a file descriptor to use during fork/exec that is
1573 // in our process, so lets just use it!
1574 if (remote
->Comm().useFD(communication_fd
))
1575 mode
= eRNBRunLoopModeExit
;
1577 remote
->StartReadRemoteDataThread();
1580 if (mode
!= eRNBRunLoopModeExit
)
1581 RNBLogSTDOUT("Waiting for debugger instructions for process %d.\n",
1586 case eRNBRunLoopModeInferiorLaunching
: {
1587 mode
= RNBRunLoopLaunchInferior(remote
, ctx
.GetSTDINPath(),
1588 ctx
.GetSTDOUTPath(), ctx
.GetSTDERRPath(),
1591 if (mode
== eRNBRunLoopModeInferiorExecuting
) {
1592 if (port
!= INT32_MAX
) {
1593 if (!ConnectRemote(remote
, host
.c_str(), port
, reverse_connect
,
1594 named_pipe_path
.c_str(), unix_socket_name
.c_str()))
1595 mode
= eRNBRunLoopModeExit
;
1596 } else if (str
[0] == '/') {
1597 if (remote
->Comm().OpenFile(str
))
1598 mode
= eRNBRunLoopModeExit
;
1599 } else if (communication_fd
>= 0) {
1600 // We were passed a file descriptor to use during fork/exec that is
1602 // in our process, so lets just use it!
1603 if (remote
->Comm().useFD(communication_fd
))
1604 mode
= eRNBRunLoopModeExit
;
1606 remote
->StartReadRemoteDataThread();
1609 if (mode
!= eRNBRunLoopModeExit
) {
1610 const char *proc_name
= "<unknown>";
1611 if (ctx
.ArgumentCount() > 0)
1612 proc_name
= ctx
.ArgumentAtIndex(0);
1613 DNBLog("[LaunchAttach] Successfully launched %s (pid = %d).\n",
1614 proc_name
, ctx
.ProcessID());
1615 RNBLogSTDOUT("Got a connection, launched process %s (pid = %d).\n",
1616 proc_name
, ctx
.ProcessID());
1619 const char *error_str
= remote
->Context().LaunchStatus().AsString();
1620 RNBLogSTDERR("error: failed to launch process %s: %s\n", argv_sub_zero
,
1621 error_str
? error_str
: "unknown error.");
1625 case eRNBRunLoopModeInferiorExecuting
:
1626 mode
= RNBRunLoopInferiorExecuting(remote
);
1629 case eRNBRunLoopModePlatformMode
:
1630 if (port
!= INT32_MAX
) {
1631 if (!ConnectRemote(remote
, host
.c_str(), port
, reverse_connect
,
1632 named_pipe_path
.c_str(), unix_socket_name
.c_str()))
1633 mode
= eRNBRunLoopModeExit
;
1634 } else if (str
[0] == '/') {
1635 if (remote
->Comm().OpenFile(str
))
1636 mode
= eRNBRunLoopModeExit
;
1637 } else if (communication_fd
>= 0) {
1638 // We were passed a file descriptor to use during fork/exec that is
1640 // in our process, so lets just use it!
1641 if (remote
->Comm().useFD(communication_fd
))
1642 mode
= eRNBRunLoopModeExit
;
1644 remote
->StartReadRemoteDataThread();
1647 if (mode
!= eRNBRunLoopModeExit
)
1648 mode
= RNBRunLoopPlatform(remote
);
1652 mode
= eRNBRunLoopModeExit
;
1654 case eRNBRunLoopModeExit
:
1659 remote
->StopReadRemoteDataThread();
1660 remote
->Context().SetProcessID(INVALID_NUB_PROCESS
);
1661 RNBLogSTDOUT("Exiting.\n");