1//===-- darwin-debug.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// Darwin launch helper
10//
11// This program was written to allow programs to be launched in a new
12// Terminal.app window and have the application be stopped for debugging
13// at the program entry point.
14//
15// Although it uses posix_spawn(), it uses Darwin specific posix spawn
16// attribute flags to accomplish its task. It uses an "exec only" flag
17// which avoids forking this process, and it uses a "stop at entry"
18// flag to stop the program at the entry point.
19//
20// Since it uses darwin specific flags this code should not be compiled
21// on other systems.
22#if defined(__APPLE__)
23
24#include <climits>
25#include <crt_externs.h>
26#include <csignal>
27#include <cstdio>
28#include <cstdlib>
29#include <cstring>
30#include <getopt.h>
31#include <mach/machine.h>
32#include <spawn.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/types.h>
36#include <sys/un.h>
37
38#include <string>
39
40#ifndef _POSIX_SPAWN_DISABLE_ASLR
41#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
42#endif
43
44#define streq(a, b) strcmp(a, b) == 0
45
46static struct option g_long_options[] = {
47    {"arch", required_argument, NULL, 'a'},
48    {"disable-aslr", no_argument, NULL, 'd'},
49    {"no-env", no_argument, NULL, 'e'},
50    {"help", no_argument, NULL, 'h'},
51    {"setsid", no_argument, NULL, 's'},
52    {"unix-socket", required_argument, NULL, 'u'},
53    {"working-dir", required_argument, NULL, 'w'},
54    {"env", required_argument, NULL, 'E'},
55    {NULL, 0, NULL, 0}};
56
57static void usage() {
58  puts("NAME\n"
59       "    darwin-debug -- posix spawn a process that is stopped at the entry "
60       "point\n"
61       "                    for debugging.\n"
62       "\n"
63       "SYNOPSIS\n"
64       "    darwin-debug --unix-socket=<SOCKET> [--arch=<ARCH>] "
65       "[--working-dir=<PATH>] [--disable-aslr] [--no-env] [--setsid] [--help] "
66       "-- <PROGRAM> [<PROGRAM-ARG> <PROGRAM-ARG> ....]\n"
67       "\n"
68       "DESCRIPTION\n"
69       "    darwin-debug will exec itself into a child process <PROGRAM> that "
70       "is\n"
71       "    halted for debugging. It does this by using posix_spawn() along "
72       "with\n"
73       "    darwin specific posix_spawn flags that allows exec only (no fork), "
74       "and\n"
75       "    stop at the program entry point. Any program arguments "
76       "<PROGRAM-ARG> are\n"
77       "    passed on to the exec as the arguments for the new process. The "
78       "current\n"
79       "    environment will be passed to the new process unless the "
80       "\"--no-env\"\n"
81       "    option is used. A unix socket must be supplied using the\n"
82       "    --unix-socket=<SOCKET> option so the calling program can handshake "
83       "with\n"
84       "    this process and get its process id.\n"
85       "\n"
86       "EXAMPLE\n"
87       "   darwin-debug --arch=i386 -- /bin/ls -al /tmp\n");
88  exit(1);
89}
90
91static void exit_with_errno(int err, const char *prefix) {
92  if (err) {
93    fprintf(stderr, "%s%s", prefix ? prefix : "", strerror(err));
94    exit(err);
95  }
96}
97
98pid_t posix_spawn_for_debug(char *const *argv, char *const *envp,
99                            const char *working_dir, cpu_type_t cpu_type,
100                            int disable_aslr) {
101  pid_t pid = 0;
102
103  const char *path = argv[0];
104
105  posix_spawnattr_t attr;
106
107  exit_with_errno(::posix_spawnattr_init(&attr),
108                  "::posix_spawnattr_init (&attr) error: ");
109
110  // Here we are using a darwin specific feature that allows us to exec only
111  // since we want this program to turn into the program we want to debug,
112  // and also have the new program start suspended (right at __dyld_start)
113  // so we can debug it
114  short flags = POSIX_SPAWN_START_SUSPENDED | POSIX_SPAWN_SETEXEC |
115                POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
116
117  // Disable ASLR if we were asked to
118  if (disable_aslr)
119    flags |= _POSIX_SPAWN_DISABLE_ASLR;
120
121  sigset_t no_signals;
122  sigset_t all_signals;
123  sigemptyset(&no_signals);
124  sigfillset(&all_signals);
125  ::posix_spawnattr_setsigmask(&attr, &no_signals);
126  ::posix_spawnattr_setsigdefault(&attr, &all_signals);
127
128  // Set the flags we just made into our posix spawn attributes
129  exit_with_errno(::posix_spawnattr_setflags(&attr, flags),
130                  "::posix_spawnattr_setflags (&attr, flags) error: ");
131
132  // Another darwin specific thing here where we can select the architecture
133  // of the binary we want to re-exec as.
134  if (cpu_type != 0) {
135    size_t ocount = 0;
136    exit_with_errno(
137        ::posix_spawnattr_setbinpref_np(&attr, 1, &cpu_type, &ocount),
138        "posix_spawnattr_setbinpref_np () error: ");
139  }
140
141  // I wish there was a posix_spawn flag to change the working directory of
142  // the inferior process we will spawn, but there currently isn't. If there
143  // ever is a better way to do this, we should use it. I would rather not
144  // manually fork, chdir in the child process, and then posix_spawn with exec
145  // as the whole reason for doing posix_spawn is to not hose anything up
146  // after the fork and prior to the exec...
147  if (working_dir)
148    ::chdir(working_dir);
149
150  exit_with_errno(::posix_spawnp(&pid, path, NULL, &attr, (char *const *)argv,
151                                 (char *const *)envp),
152                  "posix_spawn() error: ");
153
154  // This code will only be reached if the posix_spawn exec failed...
155  ::posix_spawnattr_destroy(&attr);
156
157  return pid;
158}
159
160int main(int argc, char *const *argv, char *const *envp, const char **apple) {
161#if defined(DEBUG_LLDB_LAUNCHER)
162  const char *program_name = strrchr(apple[0], '/');
163
164  if (program_name)
165    program_name++; // Skip the last slash..
166  else
167    program_name = apple[0];
168
169  printf("%s called with:\n", program_name);
170  for (int i = 0; i < argc; ++i)
171    printf("argv[%u] = '%s'\n", i, argv[i]);
172#endif
173
174  cpu_type_t cpu_type = 0;
175  bool show_usage = false;
176  int ch;
177  int disable_aslr = 0; // By default we disable ASLR
178  bool pass_env = true;
179  std::string unix_socket_name;
180  std::string working_dir;
181
182#if __GLIBC__
183  optind = 0;
184#else
185  optreset = 1;
186  optind = 1;
187#endif
188
189  while ((ch = getopt_long_only(argc, argv, "a:deE:hsu:?", g_long_options,
190                                NULL)) != -1) {
191    switch (ch) {
192    case 0:
193      break;
194
195    case 'a': // "-a i386" or "--arch=i386"
196      if (optarg) {
197        if (streq(optarg, "i386"))
198          cpu_type = CPU_TYPE_I386;
199        else if (streq(optarg, "x86_64"))
200          cpu_type = CPU_TYPE_X86_64;
201        else if (streq(optarg, "x86_64h"))
202          cpu_type = 0; // Don't set CPU type when we have x86_64h
203        else if (strstr(optarg, "arm") == optarg)
204          cpu_type = CPU_TYPE_ARM;
205        else {
206          ::fprintf(stderr, "error: unsupported cpu type '%s'\n", optarg);
207          ::exit(1);
208        }
209      }
210      break;
211
212    case 'd':
213      disable_aslr = 1;
214      break;
215
216    case 'e':
217      pass_env = false;
218      break;
219
220    case 'E': {
221      // Since we will exec this program into our new program, we can just set
222      // environment
223      // variables in this process and they will make it into the child process.
224      std::string name;
225      std::string value;
226      const char *equal_pos = strchr(optarg, '=');
227      if (equal_pos) {
228        name.assign(optarg, equal_pos - optarg);
229        value.assign(equal_pos + 1);
230      } else {
231        name = optarg;
232      }
233      ::setenv(name.c_str(), value.c_str(), 1);
234    } break;
235
236    case 's':
237      // Create a new session to avoid having control-C presses kill our current
238      // terminal session when this program is launched from a .command file
239      ::setsid();
240      break;
241
242    case 'u':
243      unix_socket_name.assign(optarg);
244      break;
245
246    case 'w': {
247      struct stat working_dir_stat;
248      if (stat(optarg, &working_dir_stat) == 0)
249        working_dir.assign(optarg);
250      else
251        ::fprintf(stderr, "warning: working directory doesn't exist: '%s'\n",
252                  optarg);
253    } break;
254
255    case 'h':
256    case '?':
257    default:
258      show_usage = true;
259      break;
260    }
261  }
262  argc -= optind;
263  argv += optind;
264
265  if (show_usage || argc <= 0 || unix_socket_name.empty())
266    usage();
267
268#if defined(DEBUG_LLDB_LAUNCHER)
269  printf("\n%s post options:\n", program_name);
270  for (int i = 0; i < argc; ++i)
271    printf("argv[%u] = '%s'\n", i, argv[i]);
272#endif
273
274  // Open the socket that was passed in as an option
275  struct sockaddr_un saddr_un;
276  int s = ::socket(AF_UNIX, SOCK_STREAM, 0);
277  if (s < 0) {
278    perror("error: socket (AF_UNIX, SOCK_STREAM, 0)");
279    exit(1);
280  }
281
282  saddr_un.sun_family = AF_UNIX;
283  ::strncpy(saddr_un.sun_path, unix_socket_name.c_str(),
284            sizeof(saddr_un.sun_path) - 1);
285  saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0';
286  saddr_un.sun_len = SUN_LEN(&saddr_un);
287
288  if (::connect(s, (struct sockaddr *)&saddr_un, SUN_LEN(&saddr_un)) < 0) {
289    perror("error: connect (socket, &saddr_un, saddr_un_len)");
290    exit(1);
291  }
292
293  // We were able to connect to the socket, now write our PID so whomever
294  // launched us will know this process's ID
295  char pid_str[64];
296  const int pid_str_len =
297      ::snprintf(pid_str, sizeof(pid_str), "%i", ::getpid());
298  const int bytes_sent = ::send(s, pid_str, pid_str_len, 0);
299
300  if (pid_str_len != bytes_sent) {
301    perror("error: send (s, pid_str, pid_str_len, 0)");
302    exit(1);
303  }
304
305  // We are done with the socket
306  close(s);
307
308  system("clear");
309  printf("Launching: '%s'\n", argv[0]);
310  if (working_dir.empty()) {
311    char cwd[PATH_MAX];
312    const char *cwd_ptr = getcwd(cwd, sizeof(cwd));
313    printf("Working directory: '%s'\n", cwd_ptr);
314  } else {
315    printf("Working directory: '%s'\n", working_dir.c_str());
316  }
317  printf("%i arguments:\n", argc);
318
319  for (int i = 0; i < argc; ++i)
320    printf("argv[%u] = '%s'\n", i, argv[i]);
321
322  // Now we posix spawn to exec this process into the inferior that we want
323  // to debug.
324  posix_spawn_for_debug(
325      argv,
326      pass_env ? *_NSGetEnviron() : NULL, // Pass current environment as we may
327                                          // have modified it if "--env" options
328                                          // was used, do NOT pass "envp" here
329      working_dir.empty() ? NULL : working_dir.c_str(), cpu_type, disable_aslr);
330
331  return 0;
332}
333
334#endif // #if defined (__APPLE__)
335