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