Coverage Report

Created: 2020-06-26 05:44

/home/arjun/llvm-project/llvm/lib/Support/Unix/Program.inc
Line
Count
Source (jump to first uncovered line)
1
//===- llvm/Support/Unix/Program.cpp -----------------------------*- C++ -*-===//
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
// This file implements the Unix specific portion of the Program class.
10
//
11
//===----------------------------------------------------------------------===//
12
13
//===----------------------------------------------------------------------===//
14
//=== WARNING: Implementation here must contain only generic UNIX code that
15
//===          is guaranteed to work on *all* UNIX variants.
16
//===----------------------------------------------------------------------===//
17
18
#include "Unix.h"
19
#include "llvm/ADT/StringExtras.h"
20
#include "llvm/Config/config.h"
21
#include "llvm/Support/Compiler.h"
22
#include "llvm/Support/Errc.h"
23
#include "llvm/Support/FileSystem.h"
24
#include "llvm/Support/Path.h"
25
#include "llvm/Support/StringSaver.h"
26
#include "llvm/Support/raw_ostream.h"
27
#if HAVE_SYS_STAT_H
28
#include <sys/stat.h>
29
#endif
30
#if HAVE_SYS_RESOURCE_H
31
#include <sys/resource.h>
32
#endif
33
#if HAVE_SIGNAL_H
34
#include <signal.h>
35
#endif
36
#if HAVE_FCNTL_H
37
#include <fcntl.h>
38
#endif
39
#if HAVE_UNISTD_H
40
#include <unistd.h>
41
#endif
42
#ifdef HAVE_POSIX_SPAWN
43
#include <spawn.h>
44
45
#if defined(__APPLE__)
46
#include <TargetConditionals.h>
47
#endif
48
49
#if defined(__APPLE__) && !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)
50
#define USE_NSGETENVIRON 1
51
#else
52
#define USE_NSGETENVIRON 0
53
#endif
54
55
#if !USE_NSGETENVIRON
56
  extern char **environ;
57
#else
58
#include <crt_externs.h> // _NSGetEnviron
59
#endif
60
#endif
61
62
namespace llvm {
63
64
using namespace sys;
65
66
0
ProcessInfo::ProcessInfo() : Pid(0), ReturnCode(0) {}
67
68
ErrorOr<std::string> sys::findProgramByName(StringRef Name,
69
0
                                            ArrayRef<StringRef> Paths) {
70
0
  assert(!Name.empty() && "Must have a name!");
71
0
  // Use the given path verbatim if it contains any slashes; this matches
72
0
  // the behavior of sh(1) and friends.
73
0
  if (Name.find('/') != StringRef::npos) return std::string(Name);
74
0
75
0
  SmallVector<StringRef, 16> EnvironmentPaths;
76
0
  if (Paths.empty())
77
0
    if (const char *PathEnv = std::getenv("PATH")) {
78
0
      SplitString(PathEnv, EnvironmentPaths, ":");
79
0
      Paths = EnvironmentPaths;
80
0
    }
81
0
82
0
  for (auto Path : Paths) {
83
0
    if (Path.empty())
84
0
      continue;
85
0
86
0
    // Check to see if this first directory contains the executable...
87
0
    SmallString<128> FilePath(Path);
88
0
    sys::path::append(FilePath, Name);
89
0
    if (sys::fs::can_execute(FilePath.c_str()))
90
0
      return std::string(FilePath.str());  // Found the executable!
91
0
  }
92
0
  return errc::no_such_file_or_directory;
93
0
}
94
95
0
static bool RedirectIO(Optional<StringRef> Path, int FD, std::string* ErrMsg) {
96
0
  if (!Path) // Noop
97
0
    return false;
98
0
  std::string File;
99
0
  if (Path->empty())
100
0
    // Redirect empty paths to /dev/null
101
0
    File = "/dev/null";
102
0
  else
103
0
    File = std::string(*Path);
104
0
105
0
  // Open the file
106
0
  int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
107
0
  if (InFD == -1) {
108
0
    MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
109
0
              + (FD == 0 ? "input" : "output"));
110
0
    return true;
111
0
  }
112
0
113
0
  // Install it as the requested FD
114
0
  if (dup2(InFD, FD) == -1) {
115
0
    MakeErrMsg(ErrMsg, "Cannot dup2");
116
0
    close(InFD);
117
0
    return true;
118
0
  }
119
0
  close(InFD);      // Close the original FD
120
0
  return false;
121
0
}
122
123
#ifdef HAVE_POSIX_SPAWN
124
static bool RedirectIO_PS(const std::string *Path, int FD, std::string *ErrMsg,
125
0
                          posix_spawn_file_actions_t *FileActions) {
126
0
  if (!Path) // Noop
127
0
    return false;
128
0
  const char *File;
129
0
  if (Path->empty())
130
0
    // Redirect empty paths to /dev/null
131
0
    File = "/dev/null";
132
0
  else
133
0
    File = Path->c_str();
134
0
135
0
  if (int Err = posix_spawn_file_actions_addopen(
136
0
          FileActions, FD, File,
137
0
          FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
138
0
    return MakeErrMsg(ErrMsg, "Cannot posix_spawn_file_actions_addopen", Err);
139
0
  return false;
140
0
}
141
#endif
142
143
0
static void TimeOutHandler(int Sig) {
144
0
}
145
146
0
static void SetMemoryLimits(unsigned size) {
147
0
#if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
148
0
  struct rlimit r;
149
0
  __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
150
0
151
0
  // Heap size
152
0
  getrlimit (RLIMIT_DATA, &r);
153
0
  r.rlim_cur = limit;
154
0
  setrlimit (RLIMIT_DATA, &r);
155
0
#ifdef RLIMIT_RSS
156
0
  // Resident set size.
157
0
  getrlimit (RLIMIT_RSS, &r);
158
0
  r.rlim_cur = limit;
159
0
  setrlimit (RLIMIT_RSS, &r);
160
0
#endif
161
0
#endif
162
0
}
163
164
}
165
166
static std::vector<const char *>
167
0
toNullTerminatedCStringArray(ArrayRef<StringRef> Strings, StringSaver &Saver) {
168
0
  std::vector<const char *> Result;
169
0
  for (StringRef S : Strings)
170
0
    Result.push_back(Saver.save(S).data());
171
0
  Result.push_back(nullptr);
172
0
  return Result;
173
0
}
174
175
static bool Execute(ProcessInfo &PI, StringRef Program,
176
                    ArrayRef<StringRef> Args, Optional<ArrayRef<StringRef>> Env,
177
                    ArrayRef<Optional<StringRef>> Redirects,
178
0
                    unsigned MemoryLimit, std::string *ErrMsg) {
179
0
  if (!llvm::sys::fs::exists(Program)) {
180
0
    if (ErrMsg)
181
0
      *ErrMsg = std::string("Executable \"") + Program.str() +
182
0
                std::string("\" doesn't exist!");
183
0
    return false;
184
0
  }
185
0
186
0
  BumpPtrAllocator Allocator;
187
0
  StringSaver Saver(Allocator);
188
0
  std::vector<const char *> ArgVector, EnvVector;
189
0
  const char **Argv = nullptr;
190
0
  const char **Envp = nullptr;
191
0
  ArgVector = toNullTerminatedCStringArray(Args, Saver);
192
0
  Argv = ArgVector.data();
193
0
  if (Env) {
194
0
    EnvVector = toNullTerminatedCStringArray(*Env, Saver);
195
0
    Envp = EnvVector.data();
196
0
  }
197
0
198
0
  // If this OS has posix_spawn and there is no memory limit being implied, use
199
0
  // posix_spawn.  It is more efficient than fork/exec.
200
0
#ifdef HAVE_POSIX_SPAWN
201
0
  if (MemoryLimit == 0) {
202
0
    posix_spawn_file_actions_t FileActionsStore;
203
0
    posix_spawn_file_actions_t *FileActions = nullptr;
204
0
205
0
    // If we call posix_spawn_file_actions_addopen we have to make sure the
206
0
    // c strings we pass to it stay alive until the call to posix_spawn,
207
0
    // so we copy any StringRefs into this variable.
208
0
    std::string RedirectsStorage[3];
209
0
210
0
    if (!Redirects.empty()) {
211
0
      assert(Redirects.size() == 3);
212
0
      std::string *RedirectsStr[3] = {nullptr, nullptr, nullptr};
213
0
      for (int I = 0; I < 3; ++I) {
214
0
        if (Redirects[I]) {
215
0
          RedirectsStorage[I] = std::string(*Redirects[I]);
216
0
          RedirectsStr[I] = &RedirectsStorage[I];
217
0
        }
218
0
      }
219
0
220
0
      FileActions = &FileActionsStore;
221
0
      posix_spawn_file_actions_init(FileActions);
222
0
223
0
      // Redirect stdin/stdout.
224
0
      if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
225
0
          RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
226
0
        return false;
227
0
      if (!Redirects[1] || !Redirects[2] || *Redirects[1] != *Redirects[2]) {
228
0
        // Just redirect stderr
229
0
        if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
230
0
          return false;
231
0
      } else {
232
0
        // If stdout and stderr should go to the same place, redirect stderr
233
0
        // to the FD already open for stdout.
234
0
        if (int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
235
0
          return !MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout", Err);
236
0
      }
237
0
    }
238
0
239
0
    if (!Envp)
240
0
#if !USE_NSGETENVIRON
241
0
      Envp = const_cast<const char **>(environ);
242
#else
243
      // environ is missing in dylibs.
244
      Envp = const_cast<const char **>(*_NSGetEnviron());
245
#endif
246
247
0
    constexpr int maxRetries = 8;
248
0
    int retries = 0;
249
0
    pid_t PID;
250
0
    int Err;
251
0
    do {
252
0
      PID = 0; // Make Valgrind happy.
253
0
      Err = posix_spawn(&PID, Program.str().c_str(), FileActions,
254
0
                        /*attrp*/ nullptr, const_cast<char **>(Argv),
255
0
                        const_cast<char **>(Envp));
256
0
    } while (Err == EINTR && ++retries < maxRetries);
257
0
258
0
    if (FileActions)
259
0
      posix_spawn_file_actions_destroy(FileActions);
260
0
261
0
    if (Err)
262
0
     return !MakeErrMsg(ErrMsg, "posix_spawn failed", Err);
263
0
264
0
    PI.Pid = PID;
265
0
    PI.Process = PID;
266
0
267
0
    return true;
268
0
  }
269
0
#endif
270
0
271
0
  // Create a child process.
272
0
  int child = fork();
273
0
  switch (child) {
274
0
    // An error occurred:  Return to the caller.
275
0
    case -1:
276
0
      MakeErrMsg(ErrMsg, "Couldn't fork");
277
0
      return false;
278
0
279
0
    // Child process: Execute the program.
280
0
    case 0: {
281
0
      // Redirect file descriptors...
282
0
      if (!Redirects.empty()) {
283
0
        // Redirect stdin
284
0
        if (RedirectIO(Redirects[0], 0, ErrMsg)) { return false; }
285
0
        // Redirect stdout
286
0
        if (RedirectIO(Redirects[1], 1, ErrMsg)) { return false; }
287
0
        if (Redirects[1] && Redirects[2] && *Redirects[1] == *Redirects[2]) {
288
0
          // If stdout and stderr should go to the same place, redirect stderr
289
0
          // to the FD already open for stdout.
290
0
          if (-1 == dup2(1,2)) {
291
0
            MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
292
0
            return false;
293
0
          }
294
0
        } else {
295
0
          // Just redirect stderr
296
0
          if (RedirectIO(Redirects[2], 2, ErrMsg)) { return false; }
297
0
        }
298
0
      }
299
0
300
0
      // Set memory limits
301
0
      if (MemoryLimit!=0) {
302
0
        SetMemoryLimits(MemoryLimit);
303
0
      }
304
0
305
0
      // Execute!
306
0
      std::string PathStr = std::string(Program);
307
0
      if (Envp != nullptr)
308
0
        execve(PathStr.c_str(), const_cast<char **>(Argv),
309
0
               const_cast<char **>(Envp));
310
0
      else
311
0
        execv(PathStr.c_str(), const_cast<char **>(Argv));
312
0
      // If the execve() failed, we should exit. Follow Unix protocol and
313
0
      // return 127 if the executable was not found, and 126 otherwise.
314
0
      // Use _exit rather than exit so that atexit functions and static
315
0
      // object destructors cloned from the parent process aren't
316
0
      // redundantly run, and so that any data buffered in stdio buffers
317
0
      // cloned from the parent aren't redundantly written out.
318
0
      _exit(errno == ENOENT ? 127 : 126);
319
0
    }
320
0
321
0
    // Parent process: Break out of the switch to do our processing.
322
0
    default:
323
0
      break;
324
0
  }
325
0
326
0
  PI.Pid = child;
327
0
  PI.Process = child;
328
0
329
0
  return true;
330
0
}
331
332
namespace llvm {
333
334
ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
335
0
                      bool WaitUntilTerminates, std::string *ErrMsg) {
336
0
  struct sigaction Act, Old;
337
0
  assert(PI.Pid && "invalid pid to wait on, process not started?");
338
0
339
0
  int WaitPidOptions = 0;
340
0
  pid_t ChildPid = PI.Pid;
341
0
  if (WaitUntilTerminates) {
342
0
    SecondsToWait = 0;
343
0
  } else if (SecondsToWait) {
344
0
    // Install a timeout handler.  The handler itself does nothing, but the
345
0
    // simple fact of having a handler at all causes the wait below to return
346
0
    // with EINTR, unlike if we used SIG_IGN.
347
0
    memset(&Act, 0, sizeof(Act));
348
0
    Act.sa_handler = TimeOutHandler;
349
0
    sigemptyset(&Act.sa_mask);
350
0
    sigaction(SIGALRM, &Act, &Old);
351
0
    alarm(SecondsToWait);
352
0
  } else if (SecondsToWait == 0)
353
0
    WaitPidOptions = WNOHANG;
354
0
355
0
  // Parent process: Wait for the child process to terminate.
356
0
  int status;
357
0
  ProcessInfo WaitResult;
358
0
359
0
  do {
360
0
    WaitResult.Pid = waitpid(ChildPid, &status, WaitPidOptions);
361
0
  } while (WaitUntilTerminates && WaitResult.Pid == -1 && errno == EINTR);
362
0
363
0
  if (WaitResult.Pid != PI.Pid) {
364
0
    if (WaitResult.Pid == 0) {
365
0
      // Non-blocking wait.
366
0
      return WaitResult;
367
0
    } else {
368
0
      if (SecondsToWait && errno == EINTR) {
369
0
        // Kill the child.
370
0
        kill(PI.Pid, SIGKILL);
371
0
372
0
        // Turn off the alarm and restore the signal handler
373
0
        alarm(0);
374
0
        sigaction(SIGALRM, &Old, nullptr);
375
0
376
0
        // Wait for child to die
377
0
        if (wait(&status) != ChildPid)
378
0
          MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
379
0
        else
380
0
          MakeErrMsg(ErrMsg, "Child timed out", 0);
381
0
382
0
        WaitResult.ReturnCode = -2; // Timeout detected
383
0
        return WaitResult;
384
0
      } else if (errno != EINTR) {
385
0
        MakeErrMsg(ErrMsg, "Error waiting for child process");
386
0
        WaitResult.ReturnCode = -1;
387
0
        return WaitResult;
388
0
      }
389
0
    }
390
0
  }
391
0
392
0
  // We exited normally without timeout, so turn off the timer.
393
0
  if (SecondsToWait && !WaitUntilTerminates) {
394
0
    alarm(0);
395
0
    sigaction(SIGALRM, &Old, nullptr);
396
0
  }
397
0
398
0
  // Return the proper exit status. Detect error conditions
399
0
  // so we can return -1 for them and set ErrMsg informatively.
400
0
  int result = 0;
401
0
  if (WIFEXITED(status)) {
402
0
    result = WEXITSTATUS(status);
403
0
    WaitResult.ReturnCode = result;
404
0
405
0
    if (result == 127) {
406
0
      if (ErrMsg)
407
0
        *ErrMsg = llvm::sys::StrError(ENOENT);
408
0
      WaitResult.ReturnCode = -1;
409
0
      return WaitResult;
410
0
    }
411
0
    if (result == 126) {
412
0
      if (ErrMsg)
413
0
        *ErrMsg = "Program could not be executed";
414
0
      WaitResult.ReturnCode = -1;
415
0
      return WaitResult;
416
0
    }
417
0
  } else if (WIFSIGNALED(status)) {
418
0
    if (ErrMsg) {
419
0
      *ErrMsg = strsignal(WTERMSIG(status));
420
0
#ifdef WCOREDUMP
421
0
      if (WCOREDUMP(status))
422
0
        *ErrMsg += " (core dumped)";
423
0
#endif
424
0
    }
425
0
    // Return a special value to indicate that the process received an unhandled
426
0
    // signal during execution as opposed to failing to execute.
427
0
    WaitResult.ReturnCode = -2;
428
0
  }
429
0
  return WaitResult;
430
0
}
431
432
0
std::error_code sys::ChangeStdinToBinary() {
433
0
  // Do nothing, as Unix doesn't differentiate between text and binary.
434
0
  return std::error_code();
435
0
}
436
437
0
std::error_code sys::ChangeStdoutToBinary() {
438
0
  // Do nothing, as Unix doesn't differentiate between text and binary.
439
0
  return std::error_code();
440
0
}
441
442
std::error_code
443
llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
444
0
                                 WindowsEncodingMethod Encoding /*unused*/) {
445
0
  std::error_code EC;
446
0
  llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::OF_Text);
447
0
448
0
  if (EC)
449
0
    return EC;
450
0
451
0
  OS << Contents;
452
0
453
0
  if (OS.has_error())
454
0
    return make_error_code(errc::io_error);
455
0
456
0
  return EC;
457
0
}
458
459
bool llvm::sys::commandLineFitsWithinSystemLimits(StringRef Program,
460
0
                                                  ArrayRef<StringRef> Args) {
461
0
  static long ArgMax = sysconf(_SC_ARG_MAX);
462
0
  // POSIX requires that _POSIX_ARG_MAX is 4096, which is the lowest possible
463
0
  // value for ARG_MAX on a POSIX compliant system.
464
0
  static long ArgMin = _POSIX_ARG_MAX;
465
0
466
0
  // This the same baseline used by xargs.
467
0
  long EffectiveArgMax = 128 * 1024;
468
0
469
0
  if (EffectiveArgMax > ArgMax)
470
0
    EffectiveArgMax = ArgMax;
471
0
  else if (EffectiveArgMax < ArgMin)
472
0
    EffectiveArgMax = ArgMin;
473
0
474
0
  // System says no practical limit.
475
0
  if (ArgMax == -1)
476
0
    return true;
477
0
478
0
  // Conservatively account for space required by environment variables.
479
0
  long HalfArgMax = EffectiveArgMax / 2;
480
0
481
0
  size_t ArgLength = Program.size() + 1;
482
0
  for (StringRef Arg : Args) {
483
0
    // Ensure that we do not exceed the MAX_ARG_STRLEN constant on Linux, which
484
0
    // does not have a constant unlike what the man pages would have you
485
0
    // believe. Since this limit is pretty high, perform the check
486
0
    // unconditionally rather than trying to be aggressive and limiting it to
487
0
    // Linux only.
488
0
    if (Arg.size() >= (32 * 4096))
489
0
      return false;
490
0
491
0
    ArgLength += Arg.size() + 1;
492
0
    if (ArgLength > size_t(HalfArgMax)) {
493
0
      return false;
494
0
    }
495
0
  }
496
0
497
0
  return true;
498
0
}
499
}