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 <spawn.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 
34 #ifndef _POSIX_SPAWN_DISABLE_ASLR
35 #define _POSIX_SPAWN_DISABLE_ASLR       0x0100
36 #endif
37 
38 #define streq(a,b) strcmp(a,b) == 0
39 
40 static struct option g_long_options[] =
41 {
42 	{ "arch",			required_argument,	NULL,           'a'		},
43 	{ "disable-aslr",   no_argument,		NULL,           'd'		},
44 	{ "no-env",         no_argument,		NULL,           'e'		},
45 	{ "help",           no_argument,		NULL,           'h'		},
46 	{ "setsid",         no_argument,		NULL,           's'		},
47 	{ NULL,				0,					NULL,            0		}
48 };
49 
50 static void
51 usage()
52 {
53     puts (
54 "NAME\n"
55 "    darwin-debug -- posix spawn a process that is stopped at the entry point\n"
56 "                    for debugging.\n"
57 "\n"
58 "SYNOPSIS\n"
59 "    darwin-debug [--arch=<ARCH>] [--disable-aslr] [--no-env] [--setsid] [--help] -- <PROGRAM> [<PROGRAM-ARG> <PROGRAM-ARG> ....]\n"
60 "\n"
61 "DESCRIPTION\n"
62 "    darwin-debug will exec itself into a child process <PROGRAM> that is\n"
63 "    halted for debugging. It does this by using posix_spawn() along with\n"
64 "    darwin specific posix_spawn flags that allows exec only (no fork), and\n"
65 "    stop at the program entry point. Any program arguments <PROGRAM-ARG> are\n"
66 "    passed on to the exec as the arguments for the new process. The current\n"
67 "    environment will be passed to the new process unless the \"--no-env\"\n"
68 "    option is used.\n"
69 "\n"
70 "EXAMPLE\n"
71 "   darwin-debug --arch=i386 -- /bin/ls -al /tmp\n"
72 );
73     exit (1);
74 }
75 
76 static void
77 exit_with_errno (int err, const char *prefix)
78 {
79     if (err)
80     {
81         fprintf (stderr,
82                  "%s%s",
83                  prefix ? prefix : "",
84                  strerror(err));
85         exit (err);
86     }
87 }
88 
89 pid_t
90 posix_spawn_for_debug (char *const *argv, char *const *envp, cpu_type_t cpu_type, int disable_aslr)
91 {
92     pid_t pid = 0;
93 
94     const char *path = argv[0];
95 
96     posix_spawnattr_t attr;
97 
98     exit_with_errno (::posix_spawnattr_init (&attr), "::posix_spawnattr_init (&attr) error: ");
99 
100     // Here we are using a darwin specific feature that allows us to exec only
101     // since we want this program to turn into the program we want to debug,
102     // and also have the new program start suspended (right at __dyld_start)
103     // so we can debug it
104     short flags = POSIX_SPAWN_START_SUSPENDED | POSIX_SPAWN_SETEXEC;
105 
106     // Disable ASLR if we were asked to
107     if (disable_aslr)
108         flags |= _POSIX_SPAWN_DISABLE_ASLR;
109 
110     // Set the flags we just made into our posix spawn attributes
111     exit_with_errno (::posix_spawnattr_setflags (&attr, flags), "::posix_spawnattr_setflags (&attr, flags) error: ");
112 
113 
114     // Another darwin specific thing here where we can select the architecture
115     // of the binary we want to re-exec as.
116     if (cpu_type != 0)
117     {
118         size_t ocount = 0;
119         exit_with_errno (::posix_spawnattr_setbinpref_np (&attr, 1, &cpu_type, &ocount), "posix_spawnattr_setbinpref_np () error: ");
120     }
121 
122     exit_with_errno (::posix_spawnp (&pid, path, NULL, &attr, (char * const*)argv, (char * const*)envp), "posix_spawn() error: ");
123 
124     // This code will only be reached if the posix_spawn exec failed...
125     ::posix_spawnattr_destroy (&attr);
126 
127     return pid;
128 }
129 
130 
131 int main (int argc, char *const *argv, char *const *envp, const char **apple)
132 {
133     const char *program_name = strrchr(apple[0], '/');
134 
135     if (program_name)
136         program_name++; // Skip the last slash..
137     else
138         program_name = apple[0];
139 
140 #if defined (DEBUG_LLDB_LAUNCHER)
141     printf("%s called with:\n", program_name);
142     for (int i=0; i<argc; ++i)
143         printf("argv[%u] = '%s'\n", i, argv[i]);
144 #endif
145 
146     cpu_type_t cpu_type = 0;
147     bool show_usage = false;
148     char ch;
149     int disable_aslr = 0; // By default we disable ASLR
150     int pass_env = 1;
151 	while ((ch = getopt_long(argc, argv, "a:dfh?", g_long_options, NULL)) != -1)
152 	{
153 		switch (ch)
154 		{
155         case 0:
156             break;
157 
158 		case 'a':	// "-a i386" or "--arch=i386"
159 			if (optarg)
160 			{
161 				if (streq (optarg, "i386"))
162                     cpu_type = CPU_TYPE_I386;
163 				else if (streq (optarg, "x86_64"))
164                     cpu_type = CPU_TYPE_X86_64;
165                 else if (strstr (optarg, "arm") == optarg)
166                     cpu_type = CPU_TYPE_ARM;
167                 else
168                 {
169                     ::fprintf (stderr, "error: unsupported cpu type '%s'\n", optarg);
170                     ::exit (1);
171                 }
172 			}
173 			break;
174 
175         case 'd':
176             disable_aslr = 1;
177             break;
178 
179         case 'e':
180             pass_env = 0;
181             break;
182 
183         case 's':
184             // Create a new session to avoid having control-C presses kill our current
185             // terminal session when this program is launched from a .command file
186             ::setsid();
187             break;
188 
189 		case 'h':
190 		case '?':
191 		default:
192 			show_usage = true;
193 			break;
194 		}
195 	}
196 	argc -= optind;
197 	argv += optind;
198 
199     if (show_usage || argc <= 0)
200         usage();
201 
202 #if defined (DEBUG_LLDB_LAUNCHER)
203     printf ("\n%s post options:\n", program_name);
204     for (int i=0; i<argc; ++i)
205         printf ("argv[%u] = '%s'\n", i, argv[i]);
206 #endif
207 
208     posix_spawn_for_debug (argv,
209                            pass_env ? envp : NULL,
210                            cpu_type,
211                            disable_aslr);
212 
213 	return 0;
214 }
215 
216 #endif // #if defined (__APPLE__)
217 
218