LLDB mainline
ProcessLaunchInfo.cpp
Go to the documentation of this file.
1//===-- ProcessLaunchInfo.cpp ---------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include <climits>
10
11#include "lldb/Host/Config.h"
14#include "lldb/Host/HostInfo.h"
17#include "lldb/Utility/Log.h"
19
20#include "llvm/Support/ConvertUTF.h"
21#include "llvm/Support/FileSystem.h"
22
23#ifdef _WIN32
25#else
26#include <climits>
27#endif
28
29using namespace lldb;
30using namespace lldb_private;
31
32// ProcessLaunchInfo member functions
33
37#ifndef _WIN32
38 m_pty = std::make_shared<PTY>();
39#endif
40}
41
43 const FileSpec &stdout_file_spec,
44 const FileSpec &stderr_file_spec,
45 const FileSpec &working_directory,
46 uint32_t launch_flags)
47 : ProcessInfo(), m_working_dir(), m_plugin_name(), m_flags(launch_flags),
49#ifndef _WIN32
50 m_pty = std::make_shared<PTY>();
51#endif
52 if (stdin_file_spec) {
53 FileAction file_action;
54 const bool read = true;
55 const bool write = false;
56 if (file_action.Open(STDIN_FILENO, stdin_file_spec, read, write))
57 AppendFileAction(file_action);
58 }
59 if (stdout_file_spec) {
60 FileAction file_action;
61 const bool read = false;
62 const bool write = true;
63 if (file_action.Open(STDOUT_FILENO, stdout_file_spec, read, write))
64 AppendFileAction(file_action);
65 }
66 if (stderr_file_spec) {
67 FileAction file_action;
68 const bool read = false;
69 const bool write = true;
70 if (file_action.Open(STDERR_FILENO, stderr_file_spec, read, write))
71 AppendFileAction(file_action);
72 }
73 if (working_directory)
74 SetWorkingDirectory(working_directory);
75}
76
78 FileAction file_action;
79 if (file_action.Close(fd)) {
80 AppendFileAction(file_action);
81 return true;
82 }
83 return false;
84}
85
87 FileAction file_action;
88 if (file_action.Duplicate(fd, dup_fd)) {
89 AppendFileAction(file_action);
90 return true;
91 }
92 return false;
93}
94
96 bool read, bool write) {
97 FileAction file_action;
98 if (file_action.Open(fd, file_spec, read, write)) {
99 AppendFileAction(file_action);
100 return true;
101 }
102 return false;
103}
104
106 bool write) {
107 FileAction file_action;
108 if (file_action.Open(fd, FileSpec(FileSystem::DEV_NULL), read, write)) {
109 AppendFileAction(file_action);
110 return true;
111 }
112 return false;
113}
114
116 if (idx < m_file_actions.size())
117 return &m_file_actions[idx];
118 return nullptr;
119}
120
122 for (size_t idx = 0, count = m_file_actions.size(); idx < count; ++idx) {
123 if (m_file_actions[idx].GetFD() == fd)
124 return &m_file_actions[idx];
125 }
126 return nullptr;
127}
128
132
134 m_working_dir = working_dir;
135}
136
138 return llvm::StringRef(m_plugin_name);
139}
140
142 m_plugin_name = std::string(plugin);
143}
144
146
148 m_shell = shell;
149 if (m_shell) {
151 m_flags.Set(lldb::eLaunchFlagLaunchInShell);
152 } else
153 m_flags.Clear(lldb::eLaunchFlagLaunchInShell);
154}
155
157 if (separate)
158 m_flags.Set(lldb::eLaunchFlagLaunchInSeparateProcessGroup);
159 else
160 m_flags.Clear(lldb::eLaunchFlagLaunchInSeparateProcessGroup);
161}
162
164 if (expand)
165 m_flags.Set(lldb::eLaunchFlagShellExpandArguments);
166 else
167 m_flags.Clear(lldb::eLaunchFlagShellExpandArguments);
168}
169
172 m_working_dir.Clear();
173 m_plugin_name.clear();
174 m_shell.Clear();
175 m_flags.Clear();
176 m_file_actions.clear();
177 m_resume_count = 0;
178 m_listener_sp.reset();
179 m_hijack_listener_sp.reset();
180}
181
183 int status) {
185 LLDB_LOG(log, "pid = {0}, signal = {1}, status = {2}", pid, signal, status);
186}
187
190 llvm::Expected<HostThread> maybe_thread =
192 if (!maybe_thread)
193 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), maybe_thread.takeError(),
194 "failed to launch host thread: {0}");
195 return true;
196 }
197 return false;
198}
199
201 if (enable)
202 m_flags.Set(lldb::eLaunchFlagDetachOnError);
203 else
204 m_flags.Clear(lldb::eLaunchFlagDetachOnError);
205}
206
209
210 if (!m_pty)
211 m_pty = std::make_shared<PTY>();
212
213 bool stdin_free = GetFileActionForFD(STDIN_FILENO) == nullptr;
214 bool stdout_free = GetFileActionForFD(STDOUT_FILENO) == nullptr;
215 bool stderr_free = GetFileActionForFD(STDERR_FILENO) == nullptr;
216 bool any_free = stdin_free || stdout_free || stderr_free;
217 if (!any_free)
218 return llvm::Error::success();
219
220 LLDB_LOG(log, "Generating a pty to use for stdin/out/err");
221
222#ifdef _WIN32
223 if (llvm::Error Err = m_pty->OpenPseudoConsole())
224 return Err;
225 return llvm::Error::success();
226#else
227 int open_flags = O_RDWR | O_NOCTTY | O_CLOEXEC;
228 if (llvm::Error Err = m_pty->OpenFirstAvailablePrimary(open_flags))
229 return Err;
230
231 const FileSpec secondary_file_spec(m_pty->GetSecondaryName());
232
233 if (stdin_free)
234 AppendOpenFileAction(STDIN_FILENO, secondary_file_spec, true, false);
235
236 if (stdout_free)
237 AppendOpenFileAction(STDOUT_FILENO, secondary_file_spec, false, true);
238
239 if (stderr_free)
240 AppendOpenFileAction(STDERR_FILENO, secondary_file_spec, false, true);
241 return llvm::Error::success();
242#endif
243}
244
246 Status &error, bool will_debug, bool first_arg_is_full_shell_command,
247 uint32_t num_resumes) {
248 error.Clear();
249
250 if (GetFlags().Test(eLaunchFlagLaunchInShell)) {
251 if (m_shell) {
252 std::string shell_executable = m_shell.GetPath();
253
254 const char **argv = GetArguments().GetConstArgumentVector();
255 if (argv == nullptr || argv[0] == nullptr)
256 return false;
257 Args shell_arguments;
258 shell_arguments.AppendArgument(shell_executable);
259 const llvm::Triple &triple = GetArchitecture().GetTriple();
260 if (triple.getOS() == llvm::Triple::Win32 &&
261 !triple.isWindowsCygwinEnvironment())
262 shell_arguments.AppendArgument(llvm::StringRef("/C"));
263 else
264 shell_arguments.AppendArgument(llvm::StringRef("-c"));
265
266 StreamString shell_command;
267 if (will_debug) {
268 // Add a modified PATH environment variable in case argv[0] is a
269 // relative path.
270 const char *argv0 = argv[0];
271 FileSpec arg_spec(argv0);
272 if (arg_spec.IsRelative()) {
273 // We have a relative path to our executable which may not work if we
274 // just try to run "a.out" (without it being converted to "./a.out")
275 FileSpec working_dir = GetWorkingDirectory();
276 // Be sure to put quotes around PATH's value in case any paths have
277 // spaces...
278 std::string new_path("PATH=\"");
279 const size_t empty_path_len = new_path.size();
280
281 if (working_dir) {
282 new_path += working_dir.GetPath();
283 } else {
284 llvm::SmallString<64> cwd;
285 if (! llvm::sys::fs::current_path(cwd))
286 new_path += cwd;
287 }
288 std::string curr_path;
289 if (HostInfo::GetEnvironmentVar("PATH", curr_path)) {
290 if (new_path.size() > empty_path_len)
291 new_path += ':';
292 new_path += curr_path;
293 }
294 new_path += "\" ";
295 shell_command.PutCString(new_path);
296 }
297
298 if (triple.getOS() != llvm::Triple::Win32 ||
299 triple.isWindowsCygwinEnvironment())
300 shell_command.PutCString("exec");
301
302 // Only Apple supports /usr/bin/arch being able to specify the
303 // architecture
304 if (GetArchitecture().IsValid() && // Valid architecture
305 GetArchitecture().GetTriple().getVendor() ==
306 llvm::Triple::Apple && // Apple only
307 GetArchitecture().GetCore() !=
308 ArchSpec::eCore_x86_64_x86_64h) // Don't do this for x86_64h
309 {
310 shell_command.Printf(" /usr/bin/arch -arch %s",
311 GetArchitecture().GetArchitectureName());
312 // Set the resume count to 2:
313 // 1 - stop in shell
314 // 2 - stop in /usr/bin/arch
315 // 3 - then we will stop in our program
316 SetResumeCount(num_resumes + 1);
317 } else {
318 // Set the resume count to 1:
319 // 1 - stop in shell
320 // 2 - then we will stop in our program
321 SetResumeCount(num_resumes);
322 }
323 }
324
325 if (first_arg_is_full_shell_command) {
326 // There should only be one argument that is the shell command itself
327 // to be used as is
328 if (argv[0] && !argv[1])
329 shell_command.Printf("%s", argv[0]);
330 else
331 return false;
332 } else {
333 for (size_t i = 0; argv[i] != nullptr; ++i) {
334 std::string safe_arg = Args::GetShellSafeArgument(m_shell, argv[i]);
335 if (safe_arg.empty())
336 safe_arg = "\"\"";
337 // Add a space to separate this arg from the previous one.
338 shell_command.PutCString(" ");
339 shell_command.PutCString(safe_arg);
340 }
341 }
342 shell_arguments.AppendArgument(shell_command.GetString());
344 m_arguments = shell_arguments;
345 return true;
346 } else {
347 error = Status::FromErrorString("invalid shell path");
348 }
349 } else {
350 error = Status::FromErrorString("not launching in shell");
351 }
352 return false;
353}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:369
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:392
static bool separate(size_t count)
Definition UUID.cpp:29
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:457
A command line argument class.
Definition Args.h:33
void AppendArgument(llvm::StringRef arg_str, char quote_char='\0')
Appends a new argument to the end of the list argument list.
Definition Args.cpp:332
static std::string GetShellSafeArgument(const FileSpec &shell, llvm::StringRef unsafe_arg)
Definition Args.cpp:394
const char ** GetConstArgumentVector() const
Gets the argument vector.
Definition Args.cpp:289
bool Duplicate(int fd, int dup_fd)
bool Open(int fd, const FileSpec &file_spec, bool read, bool write)
A file utility class.
Definition FileSpec.h:57
bool IsRelative() const
Returns true if the filespec represents a relative path.
Definition FileSpec.cpp:514
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
static const char * DEV_NULL
Definition FileSystem.h:32
bool ResolveExecutableLocation(FileSpec &file_spec)
Call into the Host to see if it can help find the file.
static FileSystem & Instance()
static llvm::Expected< HostThread > StartMonitoringChildProcess(const MonitorChildProcessCallback &callback, lldb::pid_t pid)
Start monitoring a child process.
bool ProcessIDIsValid() const
Definition ProcessInfo.h:72
lldb::pid_t GetProcessID() const
Definition ProcessInfo.h:68
lldb::ListenerSP m_hijack_listener_sp
lldb::ListenerSP m_listener_sp
ArchSpec & GetArchitecture()
Definition ProcessInfo.h:62
llvm::StringRef GetProcessPluginName() const
const FileSpec & GetShell() const
std::vector< FileAction > m_file_actions
bool AppendOpenFileAction(int fd, const FileSpec &file_spec, bool read, bool write)
bool AppendSuppressFileAction(int fd, bool read, bool write)
static void NoOpMonitorCallback(lldb::pid_t pid, int signal, int status)
A Monitor callback which does not take any action on process events.
const FileAction * GetFileActionAtIndex(size_t idx) const
void SetShell(const FileSpec &shell)
const FileAction * GetFileActionForFD(int fd) const
void SetProcessPluginName(llvm::StringRef plugin)
bool ConvertArgumentsForLaunchingInShell(Status &error, bool will_debug, bool first_arg_is_full_shell_command, uint32_t num_resumes)
bool AppendDuplicateFileAction(int fd, int dup_fd)
void AppendFileAction(const FileAction &info)
void SetLaunchInSeparateProcessGroup(bool separate)
void SetWorkingDirectory(const FileSpec &working_dir)
Host::MonitorChildProcessCallback m_monitor_callback
const FileSpec & GetWorkingDirectory() const
An error handling class.
Definition Status.h:118
static Status FromErrorString(const char *str)
Definition Status.h:141
llvm::StringRef GetString() const
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:65
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:332
uint64_t pid_t
Definition lldb-types.h:83
#define O_NOCTTY