1 //===-- ProcessLaunchInfo.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 #include "lldb/Host/Config.h"
11 
12 #ifndef LLDB_DISABLE_POSIX
13 #include <spawn.h>
14 #endif
15 
16 #include "lldb/Target/ProcessLaunchInfo.h"
17 #include "lldb/Target/FileAction.h"
18 #include "lldb/Target/Target.h"
19 
20 using namespace lldb;
21 using namespace lldb_private;
22 
23 //----------------------------------------------------------------------------
24 // ProcessLaunchInfo member functions
25 //----------------------------------------------------------------------------
26 
27 ProcessLaunchInfo::ProcessLaunchInfo () :
28     ProcessInfo(),
29     m_working_dir (),
30     m_plugin_name (),
31     m_shell (),
32     m_flags (0),
33     m_file_actions (),
34     m_pty (),
35     m_resume_count (0),
36     m_monitor_callback (NULL),
37     m_monitor_callback_baton (NULL),
38     m_monitor_signals (false),
39     m_hijack_listener_sp ()
40 {
41 }
42 
43 ProcessLaunchInfo::ProcessLaunchInfo(const char *stdin_path, const char *stdout_path, const char *stderr_path,
44                                      const char *working_directory, uint32_t launch_flags)
45     : ProcessInfo()
46     , m_working_dir()
47     , m_plugin_name()
48     , m_shell()
49     , m_flags(launch_flags)
50     , m_file_actions()
51     , m_pty()
52     , m_resume_count(0)
53     , m_monitor_callback(NULL)
54     , m_monitor_callback_baton(NULL)
55     , m_monitor_signals(false)
56     , m_hijack_listener_sp()
57 {
58     if (stdin_path)
59     {
60         FileAction file_action;
61         const bool read = true;
62         const bool write = false;
63         if (file_action.Open(STDIN_FILENO, stdin_path, read, write))
64             AppendFileAction (file_action);
65     }
66     if (stdout_path)
67     {
68         FileAction file_action;
69         const bool read = false;
70         const bool write = true;
71         if (file_action.Open(STDOUT_FILENO, stdout_path, read, write))
72             AppendFileAction (file_action);
73     }
74     if (stderr_path)
75     {
76         FileAction file_action;
77         const bool read = false;
78         const bool write = true;
79         if (file_action.Open(STDERR_FILENO, stderr_path, read, write))
80             AppendFileAction (file_action);
81     }
82     if (working_directory)
83         SetWorkingDirectory(working_directory);
84 }
85 
86 bool
87 ProcessLaunchInfo::AppendCloseFileAction (int fd)
88 {
89     FileAction file_action;
90     if (file_action.Close (fd))
91     {
92         AppendFileAction (file_action);
93         return true;
94     }
95     return false;
96 }
97 
98 bool
99 ProcessLaunchInfo::AppendDuplicateFileAction (int fd, int dup_fd)
100 {
101     FileAction file_action;
102     if (file_action.Duplicate (fd, dup_fd))
103     {
104         AppendFileAction (file_action);
105         return true;
106     }
107     return false;
108 }
109 
110 bool
111 ProcessLaunchInfo::AppendOpenFileAction (int fd, const char *path, bool read, bool write)
112 {
113     FileAction file_action;
114     if (file_action.Open (fd, path, read, write))
115     {
116         AppendFileAction (file_action);
117         return true;
118     }
119     return false;
120 }
121 
122 bool
123 ProcessLaunchInfo::AppendSuppressFileAction (int fd, bool read, bool write)
124 {
125     FileAction file_action;
126     if (file_action.Open (fd, "/dev/null", read, write))
127     {
128         AppendFileAction (file_action);
129         return true;
130     }
131     return false;
132 }
133 
134 const FileAction *
135 ProcessLaunchInfo::GetFileActionAtIndex(size_t idx) const
136 {
137     if (idx < m_file_actions.size())
138         return &m_file_actions[idx];
139     return NULL;
140 }
141 
142 const FileAction *
143 ProcessLaunchInfo::GetFileActionForFD(int fd) const
144 {
145     for (size_t idx=0, count=m_file_actions.size(); idx < count; ++idx)
146     {
147         if (m_file_actions[idx].GetFD () == fd)
148             return &m_file_actions[idx];
149     }
150     return NULL;
151 }
152 
153 const char *
154 ProcessLaunchInfo::GetWorkingDirectory () const
155 {
156     if (m_working_dir.empty())
157         return NULL;
158     return m_working_dir.c_str();
159 }
160 
161 void
162 ProcessLaunchInfo::SetWorkingDirectory (const char *working_dir)
163 {
164     if (working_dir && working_dir[0])
165         m_working_dir.assign (working_dir);
166     else
167         m_working_dir.clear();
168 }
169 
170 const char *
171 ProcessLaunchInfo::GetProcessPluginName () const
172 {
173     if (m_plugin_name.empty())
174         return NULL;
175     return m_plugin_name.c_str();
176 }
177 
178 void
179 ProcessLaunchInfo::SetProcessPluginName (const char *plugin)
180 {
181     if (plugin && plugin[0])
182         m_plugin_name.assign (plugin);
183     else
184         m_plugin_name.clear();
185 }
186 
187 const char *
188 ProcessLaunchInfo::GetShell () const
189 {
190     if (m_shell.empty())
191         return NULL;
192     return m_shell.c_str();
193 }
194 
195 void
196 ProcessLaunchInfo::SetShell (const char * path)
197 {
198     if (path && path[0])
199     {
200         m_shell.assign (path);
201         m_flags.Set (lldb::eLaunchFlagLaunchInShell);
202     }
203     else
204     {
205         m_shell.clear();
206         m_flags.Clear (lldb::eLaunchFlagLaunchInShell);
207     }
208 }
209 
210 void
211 ProcessLaunchInfo::SetLaunchInSeparateProcessGroup (bool separate)
212 {
213     if (separate)
214         m_flags.Set(lldb::eLaunchFlagLaunchInSeparateProcessGroup);
215     else
216         m_flags.Clear (lldb::eLaunchFlagLaunchInSeparateProcessGroup);
217 
218 }
219 
220 void
221 ProcessLaunchInfo::Clear ()
222 {
223     ProcessInfo::Clear();
224     m_working_dir.clear();
225     m_plugin_name.clear();
226     m_shell.clear();
227     m_flags.Clear();
228     m_file_actions.clear();
229     m_resume_count = 0;
230     m_hijack_listener_sp.reset();
231 }
232 
233 void
234 ProcessLaunchInfo::SetMonitorProcessCallback (Host::MonitorChildProcessCallback callback,
235                            void *baton,
236                            bool monitor_signals)
237 {
238     m_monitor_callback = callback;
239     m_monitor_callback_baton = baton;
240     m_monitor_signals = monitor_signals;
241 }
242 
243 bool
244 ProcessLaunchInfo::MonitorProcess () const
245 {
246     if (m_monitor_callback && ProcessIDIsValid())
247     {
248         Host::StartMonitoringChildProcess (m_monitor_callback,
249                                            m_monitor_callback_baton,
250                                            GetProcessID(),
251                                            m_monitor_signals);
252         return true;
253     }
254     return false;
255 }
256 
257 void
258 ProcessLaunchInfo::SetDetachOnError (bool enable)
259 {
260     if (enable)
261         m_flags.Set(lldb::eLaunchFlagDetachOnError);
262     else
263         m_flags.Clear(lldb::eLaunchFlagDetachOnError);
264 }
265 
266 void
267 ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
268 {
269     // If nothing for stdin or stdout or stderr was specified, then check the process for any default
270     // settings that were set with "settings set"
271     if (GetFileActionForFD(STDIN_FILENO) == NULL || GetFileActionForFD(STDOUT_FILENO) == NULL ||
272         GetFileActionForFD(STDERR_FILENO) == NULL)
273     {
274         if (m_flags.Test(eLaunchFlagDisableSTDIO))
275         {
276             AppendSuppressFileAction (STDIN_FILENO , true, false);
277             AppendSuppressFileAction (STDOUT_FILENO, false, true);
278             AppendSuppressFileAction (STDERR_FILENO, false, true);
279         }
280         else
281         {
282             // Check for any values that might have gotten set with any of:
283             // (lldb) settings set target.input-path
284             // (lldb) settings set target.output-path
285             // (lldb) settings set target.error-path
286             FileSpec in_path;
287             FileSpec out_path;
288             FileSpec err_path;
289             if (target)
290             {
291                 in_path = target->GetStandardInputPath();
292                 out_path = target->GetStandardOutputPath();
293                 err_path = target->GetStandardErrorPath();
294             }
295 
296             char path[PATH_MAX];
297             if (in_path && in_path.GetPath(path, sizeof(path)))
298                 AppendOpenFileAction(STDIN_FILENO, path, true, false);
299 
300             if (out_path && out_path.GetPath(path, sizeof(path)))
301                 AppendOpenFileAction(STDOUT_FILENO, path, false, true);
302 
303             if (err_path && err_path.GetPath(path, sizeof(path)))
304                 AppendOpenFileAction(STDERR_FILENO, path, false, true);
305 
306             if (default_to_use_pty && (!in_path || !out_path || !err_path)) {
307                 if (m_pty.OpenFirstAvailableMaster(O_RDWR| O_NOCTTY, NULL, 0)) {
308                     const char *slave_path = m_pty.GetSlaveName(NULL, 0);
309 
310                     if (!in_path) {
311                         AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
312                     }
313 
314                     if (!out_path) {
315                         AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
316                     }
317 
318                     if (!err_path) {
319                         AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
320                     }
321                 }
322             }
323         }
324     }
325 }
326 
327 
328 bool
329 ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
330                                                         bool localhost,
331                                                         bool will_debug,
332                                                         bool first_arg_is_full_shell_command,
333                                                         int32_t num_resumes)
334 {
335     error.Clear();
336 
337     if (GetFlags().Test (eLaunchFlagLaunchInShell))
338     {
339         const char *shell_executable = GetShell();
340         if (shell_executable)
341         {
342             char shell_resolved_path[PATH_MAX];
343 
344             if (localhost)
345             {
346                 FileSpec shell_filespec (shell_executable, true);
347 
348                 if (!shell_filespec.Exists())
349                 {
350                     // Resolve the path in case we just got "bash", "sh" or "tcsh"
351                     if (!shell_filespec.ResolveExecutableLocation ())
352                     {
353                         error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
354                         return false;
355                     }
356                 }
357                 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
358                 shell_executable = shell_resolved_path;
359             }
360 
361             const char **argv = GetArguments().GetConstArgumentVector ();
362             if (argv == NULL || argv[0] == NULL)
363                 return false;
364             Args shell_arguments;
365             std::string safe_arg;
366             shell_arguments.AppendArgument (shell_executable);
367             shell_arguments.AppendArgument ("-c");
368             StreamString shell_command;
369             if (will_debug)
370             {
371                 // Add a modified PATH environment variable in case argv[0]
372                 // is a relative path
373                 const char *argv0 = argv[0];
374                 if (argv0 && (argv0[0] != '/' && argv0[0] != '~'))
375                 {
376                     // We have a relative path to our executable which may not work if
377                     // we just try to run "a.out" (without it being converted to "./a.out")
378                     const char *working_dir = GetWorkingDirectory();
379                     // Be sure to put quotes around PATH's value in case any paths have spaces...
380                     std::string new_path("PATH=\"");
381                     const size_t empty_path_len = new_path.size();
382 
383                     if (working_dir && working_dir[0])
384                     {
385                         new_path += working_dir;
386                     }
387                     else
388                     {
389                         char current_working_dir[PATH_MAX];
390                         const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir));
391                         if (cwd && cwd[0])
392                             new_path += cwd;
393                     }
394                     const char *curr_path = getenv("PATH");
395                     if (curr_path)
396                     {
397                         if (new_path.size() > empty_path_len)
398                             new_path += ':';
399                         new_path += curr_path;
400                     }
401                     new_path += "\" ";
402                     shell_command.PutCString(new_path.c_str());
403                 }
404 
405                 shell_command.PutCString ("exec");
406 
407                 // Only Apple supports /usr/bin/arch being able to specify the architecture
408                 if (GetArchitecture().IsValid() &&                                          // Valid architecture
409                     GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple &&     // Apple only
410                     GetArchitecture().GetCore() != ArchSpec::eCore_x86_64_x86_64h)          // Don't do this for x86_64h
411                 {
412                     shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
413                     // Set the resume count to 2:
414                     // 1 - stop in shell
415                     // 2 - stop in /usr/bin/arch
416                     // 3 - then we will stop in our program
417                     SetResumeCount(num_resumes + 1);
418                 }
419                 else
420                 {
421                     // Set the resume count to 1:
422                     // 1 - stop in shell
423                     // 2 - then we will stop in our program
424                     SetResumeCount(num_resumes);
425                 }
426             }
427 
428             if (first_arg_is_full_shell_command)
429             {
430                 // There should only be one argument that is the shell command itself to be used as is
431                 if (argv[0] && !argv[1])
432                     shell_command.Printf("%s", argv[0]);
433                 else
434                     return false;
435             }
436             else
437             {
438                 for (size_t i=0; argv[i] != NULL; ++i)
439                 {
440                     const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
441                     shell_command.Printf(" %s", arg);
442                 }
443             }
444             shell_arguments.AppendArgument (shell_command.GetString().c_str());
445             m_executable.SetFile(shell_executable, false);
446             m_arguments = shell_arguments;
447             return true;
448         }
449         else
450         {
451             error.SetErrorString ("invalid shell path");
452         }
453     }
454     else
455     {
456         error.SetErrorString ("not launching in shell");
457     }
458     return false;
459 }
460