Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/source/Host/common/ProcessLaunchInfo.cpp
Line
Count
Source (jump to first uncovered line)
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"
12
#include "lldb/Host/FileAction.h"
13
#include "lldb/Host/FileSystem.h"
14
#include "lldb/Host/HostInfo.h"
15
#include "lldb/Host/ProcessLaunchInfo.h"
16
#include "lldb/Utility/Log.h"
17
#include "lldb/Utility/StreamString.h"
18
19
#include "llvm/Support/ConvertUTF.h"
20
#include "llvm/Support/FileSystem.h"
21
22
#if !defined(_WIN32)
23
#include <climits>
24
#endif
25
26
using namespace lldb;
27
using namespace lldb_private;
28
29
// ProcessLaunchInfo member functions
30
31
ProcessLaunchInfo::ProcessLaunchInfo()
32
    : ProcessInfo(), m_working_dir(), m_plugin_name(), m_flags(0),
33
      m_file_actions(), m_pty(new PseudoTerminal), m_monitor_callback(nullptr),
34
      m_listener_sp(), m_hijack_listener_sp(), m_scripted_process_class_name(),
35
29.8k
      m_scripted_process_dictionary_sp() {}
36
37
ProcessLaunchInfo::ProcessLaunchInfo(const FileSpec &stdin_file_spec,
38
                                     const FileSpec &stdout_file_spec,
39
                                     const FileSpec &stderr_file_spec,
40
                                     const FileSpec &working_directory,
41
                                     uint32_t launch_flags)
42
    : ProcessInfo(), m_working_dir(), m_plugin_name(), m_flags(launch_flags),
43
      m_file_actions(), m_pty(new PseudoTerminal), m_resume_count(0),
44
      m_monitor_callback(nullptr), m_monitor_callback_baton(nullptr),
45
      m_monitor_signals(false), m_listener_sp(), m_hijack_listener_sp(),
46
15
      m_scripted_process_class_name(), m_scripted_process_dictionary_sp() {
47
15
  if (stdin_file_spec) {
48
1
    FileAction file_action;
49
1
    const bool read = true;
50
1
    const bool write = false;
51
1
    if (file_action.Open(STDIN_FILENO, stdin_file_spec, read, write))
52
1
      AppendFileAction(file_action);
53
1
  }
54
15
  if (stdout_file_spec) {
55
2
    FileAction file_action;
56
2
    const bool read = false;
57
2
    const bool write = true;
58
2
    if (file_action.Open(STDOUT_FILENO, stdout_file_spec, read, write))
59
2
      AppendFileAction(file_action);
60
2
  }
61
15
  if (stderr_file_spec) {
62
1
    FileAction file_action;
63
1
    const bool read = false;
64
1
    const bool write = true;
65
1
    if (file_action.Open(STDERR_FILENO, stderr_file_spec, read, write))
66
1
      AppendFileAction(file_action);
67
1
  }
68
15
  if (working_directory)
69
5
    SetWorkingDirectory(working_directory);
70
15
}
71
72
7.75k
bool ProcessLaunchInfo::AppendCloseFileAction(int fd) {
73
7.75k
  FileAction file_action;
74
7.75k
  if (file_action.Close(fd)) {
75
7.75k
    AppendFileAction(file_action);
76
7.75k
    return true;
77
7.75k
  }
78
0
  return false;
79
7.75k
}
80
81
3.13k
bool ProcessLaunchInfo::AppendDuplicateFileAction(int fd, int dup_fd) {
82
3.13k
  FileAction file_action;
83
3.13k
  if (file_action.Duplicate(fd, dup_fd)) {
84
3.13k
    AppendFileAction(file_action);
85
3.13k
    return true;
86
3.13k
  }
87
0
  return false;
88
3.13k
}
89
90
bool ProcessLaunchInfo::AppendOpenFileAction(int fd, const FileSpec &file_spec,
91
36.1k
                                             bool read, bool write) {
92
36.1k
  FileAction file_action;
93
36.1k
  if (file_action.Open(fd, file_spec, read, write)) {
94
8.99k
    AppendFileAction(file_action);
95
8.99k
    return true;
96
8.99k
  }
97
27.1k
  return false;
98
36.1k
}
99
100
bool ProcessLaunchInfo::AppendSuppressFileAction(int fd, bool read,
101
10.0k
                                                 bool write) {
102
10.0k
  FileAction file_action;
103
10.0k
  if (file_action.Open(fd, FileSpec(FileSystem::DEV_NULL), read, write)) {
104
10.0k
    AppendFileAction(file_action);
105
10.0k
    return true;
106
10.0k
  }
107
0
  return false;
108
10.0k
}
109
110
30.0k
const FileAction *ProcessLaunchInfo::GetFileActionAtIndex(size_t idx) const {
111
30.0k
  if (idx < m_file_actions.size())
112
30.0k
    return &m_file_actions[idx];
113
0
  return nullptr;
114
30.0k
}
115
116
18.1k
const FileAction *ProcessLaunchInfo::GetFileActionForFD(int fd) const {
117
18.9k
  for (size_t idx = 0, count = m_file_actions.size(); idx < count; 
++idx818
) {
118
1.17k
    if (m_file_actions[idx].GetFD() == fd)
119
353
      return &m_file_actions[idx];
120
1.17k
  }
121
17.7k
  return nullptr;
122
18.1k
}
123
124
7.43k
const FileSpec &ProcessLaunchInfo::GetWorkingDirectory() const {
125
7.43k
  return m_working_dir;
126
7.43k
}
127
128
2.35k
void ProcessLaunchInfo::SetWorkingDirectory(const FileSpec &working_dir) {
129
2.35k
  m_working_dir = working_dir;
130
2.35k
}
131
132
2.56k
const char *ProcessLaunchInfo::GetProcessPluginName() const {
133
2.56k
  return (m_plugin_name.empty() ? 
nullptr2.56k
:
m_plugin_name.c_str()6
);
134
2.56k
}
135
136
12
void ProcessLaunchInfo::SetProcessPluginName(llvm::StringRef plugin) {
137
12
  m_plugin_name = std::string(plugin);
138
12
}
139
140
6.56k
const FileSpec &ProcessLaunchInfo::GetShell() const { return m_shell; }
141
142
1.40k
void ProcessLaunchInfo::SetShell(const FileSpec &shell) {
143
1.40k
  m_shell = shell;
144
1.40k
  if (m_shell) {
145
1.40k
    FileSystem::Instance().ResolveExecutableLocation(m_shell);
146
1.40k
    m_flags.Set(lldb::eLaunchFlagLaunchInShell);
147
1.40k
  } else
148
0
    m_flags.Clear(lldb::eLaunchFlagLaunchInShell);
149
1.40k
}
150
151
5.15k
void ProcessLaunchInfo::SetLaunchInSeparateProcessGroup(bool separate) {
152
5.15k
  if (separate)
153
5.15k
    m_flags.Set(lldb::eLaunchFlagLaunchInSeparateProcessGroup);
154
0
  else
155
0
    m_flags.Clear(lldb::eLaunchFlagLaunchInSeparateProcessGroup);
156
5.15k
}
157
158
862
void ProcessLaunchInfo::SetShellExpandArguments(bool expand) {
159
862
  if (expand)
160
862
    m_flags.Set(lldb::eLaunchFlagShellExpandArguments);
161
0
  else
162
0
    m_flags.Clear(lldb::eLaunchFlagShellExpandArguments);
163
862
}
164
165
24.8k
void ProcessLaunchInfo::Clear() {
166
24.8k
  ProcessInfo::Clear();
167
24.8k
  m_working_dir.Clear();
168
24.8k
  m_plugin_name.clear();
169
24.8k
  m_shell.Clear();
170
24.8k
  m_flags.Clear();
171
24.8k
  m_file_actions.clear();
172
24.8k
  m_resume_count = 0;
173
24.8k
  m_listener_sp.reset();
174
24.8k
  m_hijack_listener_sp.reset();
175
24.8k
  m_scripted_process_class_name.clear();
176
24.8k
  m_scripted_process_dictionary_sp.reset();
177
24.8k
}
178
179
void ProcessLaunchInfo::SetMonitorProcessCallback(
180
6.57k
    const Host::MonitorChildProcessCallback &callback, bool monitor_signals) {
181
6.57k
  m_monitor_callback = callback;
182
6.57k
  m_monitor_signals = monitor_signals;
183
6.57k
}
184
185
2.57k
bool ProcessLaunchInfo::NoOpMonitorCallback(lldb::pid_t pid, bool exited, int signal, int status) {
186
2.57k
  Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
187
2.57k
  LLDB_LOG(log, "pid = {0}, exited = {1}, signal = {2}, status = {3}", pid,
188
2.57k
           exited, signal, status);
189
2.57k
  return true;
190
2.57k
}
191
192
6.56k
bool ProcessLaunchInfo::MonitorProcess() const {
193
6.56k
  if (m_monitor_callback && ProcessIDIsValid()) {
194
6.56k
    llvm::Expected<HostThread> maybe_thread =
195
6.56k
    Host::StartMonitoringChildProcess(m_monitor_callback, GetProcessID(),
196
6.56k
                                      m_monitor_signals);
197
6.56k
    if (!maybe_thread)
198
0
      LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
199
6.56k
               "failed to launch host thread: {}",
200
6.56k
               llvm::toString(maybe_thread.takeError()));
201
6.56k
    return true;
202
6.56k
  }
203
0
  return false;
204
6.56k
}
205
206
0
void ProcessLaunchInfo::SetDetachOnError(bool enable) {
207
0
  if (enable)
208
0
    m_flags.Set(lldb::eLaunchFlagDetachOnError);
209
0
  else
210
0
    m_flags.Clear(lldb::eLaunchFlagDetachOnError);
211
0
}
212
213
2.57k
llvm::Error ProcessLaunchInfo::SetUpPtyRedirection() {
214
2.57k
  Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
215
216
2.57k
  bool stdin_free = GetFileActionForFD(STDIN_FILENO) == nullptr;
217
2.57k
  bool stdout_free = GetFileActionForFD(STDOUT_FILENO) == nullptr;
218
2.57k
  bool stderr_free = GetFileActionForFD(STDERR_FILENO) == nullptr;
219
2.57k
  bool any_free = stdin_free || 
stdout_free2
||
stderr_free1
;
220
2.57k
  if (!any_free)
221
1
    return llvm::Error::success();
222
223
2.57k
  LLDB_LOG(log, "Generating a pty to use for stdin/out/err");
224
225
2.57k
  int open_flags = O_RDWR | O_NOCTTY;
226
2.57k
#if !defined(_WIN32)
227
  // We really shouldn't be specifying platform specific flags that are
228
  // intended for a system call in generic code.  But this will have to
229
  // do for now.
230
2.57k
  open_flags |= O_CLOEXEC;
231
2.57k
#endif
232
2.57k
  if (llvm::Error Err = m_pty->OpenFirstAvailablePrimary(open_flags))
233
0
    return Err;
234
235
2.57k
  const FileSpec secondary_file_spec(m_pty->GetSecondaryName());
236
237
2.57k
  if (stdin_free)
238
2.57k
    AppendOpenFileAction(STDIN_FILENO, secondary_file_spec, true, false);
239
240
2.57k
  if (stdout_free)
241
2.42k
    AppendOpenFileAction(STDOUT_FILENO, secondary_file_spec, false, true);
242
243
2.57k
  if (stderr_free)
244
2.57k
    AppendOpenFileAction(STDERR_FILENO, secondary_file_spec, false, true);
245
2.57k
  return llvm::Error::success();
246
2.57k
}
247
248
bool ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell(
249
    Status &error, bool will_debug, bool first_arg_is_full_shell_command,
250
1.40k
    uint32_t num_resumes) {
251
1.40k
  error.Clear();
252
253
1.40k
  if (GetFlags().Test(eLaunchFlagLaunchInShell)) {
254
1.40k
    if (m_shell) {
255
1.40k
      std::string shell_executable = m_shell.GetPath();
256
257
1.40k
      const char **argv = GetArguments().GetConstArgumentVector();
258
1.40k
      if (argv == nullptr || argv[0] == nullptr)
259
0
        return false;
260
1.40k
      Args shell_arguments;
261
1.40k
      shell_arguments.AppendArgument(shell_executable);
262
1.40k
      const llvm::Triple &triple = GetArchitecture().GetTriple();
263
1.40k
      if (triple.getOS() == llvm::Triple::Win32 &&
264
1.40k
          
!triple.isWindowsCygwinEnvironment()0
)
265
0
        shell_arguments.AppendArgument(llvm::StringRef("/C"));
266
1.40k
      else
267
1.40k
        shell_arguments.AppendArgument(llvm::StringRef("-c"));
268
269
1.40k
      StreamString shell_command;
270
1.40k
      if (will_debug) {
271
        // Add a modified PATH environment variable in case argv[0] is a
272
        // relative path.
273
0
        const char *argv0 = argv[0];
274
0
        FileSpec arg_spec(argv0);
275
0
        if (arg_spec.IsRelative()) {
276
          // We have a relative path to our executable which may not work if we
277
          // just try to run "a.out" (without it being converted to "./a.out")
278
0
          FileSpec working_dir = GetWorkingDirectory();
279
          // Be sure to put quotes around PATH's value in case any paths have
280
          // spaces...
281
0
          std::string new_path("PATH=\"");
282
0
          const size_t empty_path_len = new_path.size();
283
284
0
          if (working_dir) {
285
0
            new_path += working_dir.GetPath();
286
0
          } else {
287
0
            llvm::SmallString<64> cwd;
288
0
            if (! llvm::sys::fs::current_path(cwd))
289
0
              new_path += cwd;
290
0
          }
291
0
          std::string curr_path;
292
0
          if (HostInfo::GetEnvironmentVar("PATH", curr_path)) {
293
0
            if (new_path.size() > empty_path_len)
294
0
              new_path += ':';
295
0
            new_path += curr_path;
296
0
          }
297
0
          new_path += "\" ";
298
0
          shell_command.PutCString(new_path);
299
0
        }
300
301
0
        if (triple.getOS() != llvm::Triple::Win32 ||
302
0
            triple.isWindowsCygwinEnvironment())
303
0
          shell_command.PutCString("exec");
304
305
        // Only Apple supports /usr/bin/arch being able to specify the
306
        // architecture
307
0
        if (GetArchitecture().IsValid() && // Valid architecture
308
0
            GetArchitecture().GetTriple().getVendor() ==
309
0
                llvm::Triple::Apple && // Apple only
310
0
            GetArchitecture().GetCore() !=
311
0
                ArchSpec::eCore_x86_64_x86_64h) // Don't do this for x86_64h
312
0
        {
313
0
          shell_command.Printf(" /usr/bin/arch -arch %s",
314
0
                               GetArchitecture().GetArchitectureName());
315
          // Set the resume count to 2:
316
          // 1 - stop in shell
317
          // 2 - stop in /usr/bin/arch
318
          // 3 - then we will stop in our program
319
0
          SetResumeCount(num_resumes + 1);
320
0
        } else {
321
          // Set the resume count to 1:
322
          // 1 - stop in shell
323
          // 2 - then we will stop in our program
324
0
          SetResumeCount(num_resumes);
325
0
        }
326
0
      }
327
328
1.40k
      if (first_arg_is_full_shell_command) {
329
        // There should only be one argument that is the shell command itself
330
        // to be used as is
331
0
        if (argv[0] && !argv[1])
332
0
          shell_command.Printf("%s", argv[0]);
333
0
        else
334
0
          return false;
335
1.40k
      } else {
336
5.24k
        for (size_t i = 0; argv[i] != nullptr; 
++i3.83k
) {
337
3.83k
          std::string safe_arg = Args::GetShellSafeArgument(m_shell, argv[i]);
338
          // Add a space to separate this arg from the previous one.
339
3.83k
          shell_command.PutCString(" ");
340
3.83k
          shell_command.PutCString(safe_arg);
341
3.83k
        }
342
1.40k
      }
343
1.40k
      shell_arguments.AppendArgument(shell_command.GetString());
344
1.40k
      m_executable = m_shell;
345
1.40k
      m_arguments = shell_arguments;
346
1.40k
      return true;
347
1.40k
    } else {
348
0
      error.SetErrorString("invalid shell path");
349
0
    }
350
1.40k
  } else {
351
0
    error.SetErrorString("not launching in shell");
352
0
  }
353
0
  return false;
354
1.40k
}