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