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

source code of lldb/tools/debugserver/source/debugserver.cpp