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 (const char *path, char *const *argv, char *const *envp, cpu_type_t cpu_type, int disable_aslr)
91 {
92     pid_t pid = 0;
93 
94     posix_spawnattr_t attr;
95 
96     exit_with_errno (::posix_spawnattr_init (&attr), "::posix_spawnattr_init (&attr) error: ");
97 
98     // Here we are using a darwin specific feature that allows us to exec only
99     // since we want this program to turn into the program we want to debug,
100     // and also have the new program start suspended (right at __dyld_start)
101     // so we can debug it
102     short flags = POSIX_SPAWN_START_SUSPENDED | POSIX_SPAWN_SETEXEC;
103 
104     // Disable ASLR if we were asked to
105     if (disable_aslr)
106         flags |= _POSIX_SPAWN_DISABLE_ASLR;
107 
108     // Set the flags we just made into our posix spawn attributes
109     exit_with_errno (::posix_spawnattr_setflags (&attr, flags), "::posix_spawnattr_setflags (&attr, flags) error: ");
110 
111 
112     // Another darwin specific thing here where we can select the architecture
113     // of the binary we want to re-exec as.
114     if (cpu_type != 0)
115     {
116         size_t ocount = 0;
117         exit_with_errno (::posix_spawnattr_setbinpref_np (&attr, 1, &cpu_type, &ocount), "posix_spawnattr_setbinpref_np () error: ");
118     }
119 
120     exit_with_errno (::posix_spawnp (&pid, path, NULL, &attr, (char * const*)argv, (char * const*)envp), "posix_spawn() error: ");
121 
122     // This code will only be reached if the posix_spawn exec failed...
123     ::posix_spawnattr_destroy (&attr);
124 
125     return pid;
126 }
127 
128 
129 int main (int argc, char *const *argv, char *const *envp, const char **apple)
130 {
131     const char *program_name = strrchr(apple[0], '/');
132 
133     if (program_name)
134         program_name++; // Skip the last slash..
135     else
136         program_name = apple[0];
137 
138 #if defined (DEBUG_LLDB_LAUNCHER)
139     printf("%s called with:\n", program_name);
140     for (int i=0; i<argc; ++i)
141         printf("argv[%u] = '%s'\n", i, argv[i]);
142 #endif
143 
144     cpu_type_t cpu_type = 0;
145     bool show_usage = false;
146     char ch;
147     int disable_aslr = 0; // By default we disable ASLR
148     int pass_env = 1;
149 	while ((ch = getopt_long(argc, argv, "a:dfh?", g_long_options, NULL)) != -1)
150 	{
151 		switch (ch)
152 		{
153         case 0:
154             break;
155 
156 		case 'a':	// "-a i386" or "--arch=i386"
157 			if (optarg)
158 			{
159 				if (streq (optarg, "i386"))
160                     cpu_type = CPU_TYPE_I386;
161 				else if (streq (optarg, "x86_64"))
162                     cpu_type = CPU_TYPE_X86_64;
163                 else if (strstr (optarg, "arm") == optarg)
164                     cpu_type = CPU_TYPE_ARM;
165                 else
166                 {
167                     ::fprintf (stderr, "error: unsupported cpu type '%s'\n", optarg);
168                     ::exit (1);
169                 }
170 			}
171 			break;
172 
173         case 'd':
174             disable_aslr = 1;
175             break;
176 
177         case 'e':
178             pass_env = 0;
179             break;
180 
181         case 's':
182             // Create a new session to avoid having control-C presses kill our current
183             // terminal session when this program is launched from a .command file
184             ::setsid();
185             break;
186 
187 		case 'h':
188 		case '?':
189 		default:
190 			show_usage = true;
191 			break;
192 		}
193 	}
194 	argc -= optind;
195 	argv += optind;
196 
197     if (show_usage || argc <= 0)
198         usage();
199 
200 #if defined (DEBUG_LLDB_LAUNCHER)
201     printf ("\n%s post options:\n", program_name);
202     for (int i=0; i<argc; ++i)
203         printf ("argv[%u] = '%s'\n", i, argv[i]);
204 #endif
205 
206     const char *exe_path = argv[0];
207 
208     // Skip this inferior program name...
209     ++argv;
210 
211     posix_spawn_for_debug (exe_path,
212                            argv,
213                            pass_env ? envp : NULL,
214                            cpu_type,
215                            disable_aslr);
216 
217 	return 0;
218 }
219 
220 #endif // #if defined (__APPLE__)
221 
222