brintos

brintos / llvm-project-archived public Read only

0
0
Text · 23.4 KiB · 13a142f Raw
709 lines · cpp
1//===- unittest/Support/ProgramTest.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-exception6//7//===----------------------------------------------------------------------===//8 9#include "llvm/Support/Program.h"10#include "llvm/Config/llvm-config.h"11#include "llvm/Support/CommandLine.h"12#include "llvm/Support/ConvertUTF.h"13#include "llvm/Support/ExponentialBackoff.h"14#include "llvm/Support/FileSystem.h"15#include "llvm/Support/Path.h"16#include "llvm/Support/Signals.h"17#include "gtest/gtest.h"18#include <stdlib.h>19#include <thread>20#if defined(__APPLE__)21# include <crt_externs.h>22#elif !defined(_MSC_VER)23// Forward declare environ in case it's not provided by stdlib.h.24extern char **environ;25#endif26 27#if defined(LLVM_ON_UNIX)28#include <unistd.h>29void sleep_for(unsigned int seconds) {30  sleep(seconds);31}32#elif defined(_WIN32)33#include <windows.h>34void sleep_for(unsigned int seconds) {35  Sleep(seconds * 1000);36}37#else38#error sleep_for is not implemented on your platform.39#endif40 41#define ASSERT_NO_ERROR(x)                                                     \42  if (std::error_code ASSERT_NO_ERROR_ec = x) {                                \43    SmallString<128> MessageStorage;                                           \44    raw_svector_ostream Message(MessageStorage);                               \45    Message << #x ": did not return errc::success.\n"                          \46            << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n"          \47            << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n";      \48    GTEST_FATAL_FAILURE_(MessageStorage.c_str());                              \49  } else {                                                                     \50  }51// From TestMain.cpp.52extern const char *TestMainArgv0;53 54namespace {55 56using namespace llvm;57using namespace sys;58 59static cl::opt<std::string>60ProgramTestStringArg1("program-test-string-arg1");61static cl::opt<std::string>62ProgramTestStringArg2("program-test-string-arg2");63 64class ProgramEnvTest : public testing::Test {65  std::vector<StringRef> EnvTable;66  std::vector<std::string> EnvStorage;67 68protected:69  void SetUp() override {70    auto EnvP = [] {71#if defined(_WIN32)72      _wgetenv(L"TMP"); // Populate _wenviron, initially is null73      return _wenviron;74#elif defined(__APPLE__)75      return *_NSGetEnviron();76#else77      return environ;78#endif79    }();80    ASSERT_TRUE(EnvP);81 82    auto prepareEnvVar = [this](decltype(*EnvP) Var) -> StringRef {83#if defined(_WIN32)84      // On Windows convert UTF16 encoded variable to UTF885      auto Len = wcslen(Var);86      ArrayRef<char> Ref{reinterpret_cast<char const *>(Var),87                         Len * sizeof(*Var)};88      EnvStorage.emplace_back();89      auto convStatus = convertUTF16ToUTF8String(Ref, EnvStorage.back());90      EXPECT_TRUE(convStatus);91      return EnvStorage.back();92#else93      (void)this;94      return StringRef(Var);95#endif96    };97 98    while (*EnvP != nullptr) {99      auto S = prepareEnvVar(*EnvP);100      if (!StringRef(S).starts_with("GTEST_"))101        EnvTable.emplace_back(S);102      ++EnvP;103    }104  }105 106  void TearDown() override {107    EnvTable.clear();108    EnvStorage.clear();109  }110 111  void addEnvVar(StringRef Var) { EnvTable.emplace_back(Var); }112 113  ArrayRef<StringRef> getEnviron() const { return EnvTable; }114};115 116#ifdef _WIN32117void checkSeparators(StringRef Path) {118  char UndesiredSeparator = sys::path::get_separator()[0] == '/' ? '\\' : '/';119  ASSERT_EQ(Path.find(UndesiredSeparator), StringRef::npos);120}121 122TEST_F(ProgramEnvTest, CreateProcessLongPath) {123  if (getenv("LLVM_PROGRAM_TEST_LONG_PATH"))124    exit(0);125 126  // getMainExecutable returns an absolute path; prepend the long-path prefix.127  SmallString<128> MyAbsExe(128      sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1));129  checkSeparators(MyAbsExe);130  // Force a path with backslashes, when we are going to prepend the \\?\131  // prefix.132  sys::path::native(MyAbsExe, sys::path::Style::windows_backslash);133  std::string MyExe;134  if (!StringRef(MyAbsExe).starts_with("\\\\?\\"))135    MyExe.append("\\\\?\\");136  MyExe.append(std::string(MyAbsExe.begin(), MyAbsExe.end()));137 138  StringRef ArgV[] = {MyExe,139                      "--gtest_filter=ProgramEnvTest.CreateProcessLongPath"};140 141  // Add LLVM_PROGRAM_TEST_LONG_PATH to the environment of the child.142  addEnvVar("LLVM_PROGRAM_TEST_LONG_PATH=1");143 144  // Redirect stdout to a long path.145  SmallString<128> TestDirectory;146  ASSERT_NO_ERROR(147    fs::createUniqueDirectory("program-redirect-test", TestDirectory));148  SmallString<256> LongPath(TestDirectory);149  LongPath.push_back('\\');150  // MAX_PATH = 260151  LongPath.append(260 - TestDirectory.size(), 'a');152 153  std::string Error;154  bool ExecutionFailed;155  std::optional<StringRef> Redirects[] = {std::nullopt, LongPath.str(),156                                          std::nullopt};157  int RC = ExecuteAndWait(MyExe, ArgV, getEnviron(), Redirects,158    /*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &Error,159    &ExecutionFailed);160  EXPECT_FALSE(ExecutionFailed) << Error;161  EXPECT_EQ(0, RC);162 163  // Remove the long stdout.164  ASSERT_NO_ERROR(fs::remove(Twine(LongPath)));165  ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory)));166}167#endif168 169TEST_F(ProgramEnvTest, CreateProcessTrailingSlash) {170  if (getenv("LLVM_PROGRAM_TEST_CHILD")) {171    if (ProgramTestStringArg1 == "has\\\\ trailing\\" &&172        ProgramTestStringArg2 == "has\\\\ trailing\\") {173      exit(0);  // Success!  The arguments were passed and parsed.174    }175    exit(1);176  }177 178  std::string my_exe =179      sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);180  StringRef argv[] = {181      my_exe,182      "--gtest_filter=ProgramEnvTest.CreateProcessTrailingSlash",183      "-program-test-string-arg1",184      "has\\\\ trailing\\",185      "-program-test-string-arg2",186      "has\\\\ trailing\\"};187 188  // Add LLVM_PROGRAM_TEST_CHILD to the environment of the child.189  addEnvVar("LLVM_PROGRAM_TEST_CHILD=1");190 191  std::string error;192  bool ExecutionFailed;193  // Redirect stdout and stdin to NUL, but let stderr through.194#ifdef _WIN32195  StringRef nul("NUL");196#else197  StringRef nul("/dev/null");198#endif199  std::optional<StringRef> redirects[] = {nul, nul, std::nullopt};200  int rc = ExecuteAndWait(my_exe, argv, getEnviron(), redirects,201                          /*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &error,202                          &ExecutionFailed);203  EXPECT_FALSE(ExecutionFailed) << error;204  EXPECT_EQ(0, rc);205}206 207TEST_F(ProgramEnvTest, TestExecuteNoWait) {208  using namespace llvm::sys;209 210  if (getenv("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT")) {211    sleep_for(/*seconds*/ 1);212    exit(0);213  }214 215  std::string Executable =216      sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);217  StringRef argv[] = {Executable,218                      "--gtest_filter=ProgramEnvTest.TestExecuteNoWait"};219 220  // Add LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT to the environment of the child.221  addEnvVar("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT=1");222 223  std::string Error;224  bool ExecutionFailed;225  ProcessInfo PI1 = ExecuteNoWait(Executable, argv, getEnviron(), {}, 0, &Error,226                                  &ExecutionFailed);227  ASSERT_FALSE(ExecutionFailed) << Error;228  ASSERT_NE(PI1.Pid, ProcessInfo::InvalidPid) << "Invalid process id";229 230  unsigned LoopCount = 0;231 232  // Test that Wait() with SecondsToWait=std::nullopt works. In this case,233  // LoopCount should only be incremented once.234  while (true) {235    ++LoopCount;236    ProcessInfo WaitResult =237        llvm::sys::Wait(PI1, /*SecondsToWait=*/std::nullopt, &Error);238    ASSERT_TRUE(Error.empty());239    if (WaitResult.Pid == PI1.Pid)240      break;241  }242 243  EXPECT_EQ(LoopCount, 1u) << "LoopCount should be 1";244 245  ProcessInfo PI2 = ExecuteNoWait(Executable, argv, getEnviron(),246                                  /*Redirects*/ {}, /*MemoryLimit*/ 0, &Error,247                                  &ExecutionFailed);248  ASSERT_FALSE(ExecutionFailed) << Error;249  ASSERT_NE(PI2.Pid, ProcessInfo::InvalidPid) << "Invalid process id";250 251  // Test that Wait() with SecondsToWait=0 performs a non-blocking wait. In this252  // case, LoopCount should be greater than 1 (more than one increment occurs).253  while (true) {254    ++LoopCount;255    ProcessInfo WaitResult = llvm::sys::Wait(PI2, /*SecondsToWait=*/0, &Error);256    ASSERT_TRUE(Error.empty());257    if (WaitResult.Pid == PI2.Pid)258      break;259  }260 261  ASSERT_GT(LoopCount, 1u) << "LoopCount should be >1";262}263 264TEST_F(ProgramEnvTest, TestExecuteNoWaitDetached) {265  using namespace llvm::sys;266 267  if (getenv("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT_DETACHED")) {268    sleep_for(/*seconds=*/5);269    char *Detached = getenv("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT_DETACHED_TRUE");270#if _WIN32271    HANDLE StdHandle = GetStdHandle(STD_OUTPUT_HANDLE);272 273    if (Detached && (StdHandle == INVALID_HANDLE_VALUE || StdHandle == NULL))274      exit(100);275    if (!Detached && (StdHandle != INVALID_HANDLE_VALUE && StdHandle != NULL))276      exit(200);277#else278    int ParentSID = std::stoi(279        std::string(getenv("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT_DETACHED_SID")));280 281    pid_t ChildSID = ::getsid(0);282    if (ChildSID == -1) {283      llvm::errs() << "Could not get process SID: " << strerror(errno) << '\n';284      exit(1);285    }286 287    if (Detached && (ChildSID != ParentSID))288      exit(100);289    if (!Detached && (ChildSID == ParentSID))290      exit(200);291#endif292    exit(0);293  }294 295  std::string Executable =296      sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);297  StringRef argv[] = {298      Executable, "--gtest_filter=ProgramEnvTest.TestExecuteNoWaitDetached"};299  addEnvVar("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT_DETACHED=1");300 301#if _WIN32302  // Depending on how the test is run it may already be detached from a303  // console. Temporarily allocate a new console. If a console already304  // exists AllocConsole will harmlessly fail and return false305  BOOL AllocConsoleSuccess = AllocConsole();306 307  // Confirm existence of console308  HANDLE StdHandle = GetStdHandle(STD_OUTPUT_HANDLE);309  ASSERT_TRUE(StdHandle != INVALID_HANDLE_VALUE && StdHandle != NULL);310#else311  pid_t SID = ::getsid(0);312  ASSERT_NE(SID, -1);313  std::string SIDEnvVar =314      "LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT_DETACHED_SID=" + std::to_string(SID);315  addEnvVar(SIDEnvVar);316#endif317 318  // DetachProcess = true319  {320    std::string Error;321    bool ExecutionFailed;322    std::vector<llvm::StringRef> Env = getEnviron();323    Env.emplace_back("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT_DETACHED_TRUE=1");324    ProcessInfo PI1 =325        ExecuteNoWait(Executable, argv, Env, {}, 0, &Error, &ExecutionFailed,326                      nullptr, /*DetachProcess=*/true);327    ASSERT_FALSE(ExecutionFailed) << Error;328    ASSERT_NE(PI1.Pid, ProcessInfo::InvalidPid) << "Invalid process id";329    ProcessInfo WaitResult = Wait(PI1, std::nullopt, &Error);330    ASSERT_EQ(WaitResult.ReturnCode, 100);331  }332 333  // DetachProcess = false334  {335    std::string Error;336    bool ExecutionFailed;337    ProcessInfo PI2 =338        ExecuteNoWait(Executable, argv, getEnviron(), {}, 0, &Error,339                      &ExecutionFailed, nullptr, /*DetachProcess=*/false);340    ASSERT_FALSE(ExecutionFailed) << Error;341    ASSERT_NE(PI2.Pid, ProcessInfo::InvalidPid) << "Invalid process id";342    ProcessInfo WaitResult = Wait(PI2, std::nullopt, &Error);343    ASSERT_EQ(WaitResult.ReturnCode, 200);344  }345#if _WIN32346  // If console was allocated then free the console347  if (AllocConsoleSuccess) {348    BOOL FreeConsoleSuccess = FreeConsole();349    ASSERT_NE(FreeConsoleSuccess, 0);350  }351#endif352}353 354TEST_F(ProgramEnvTest, TestExecuteAndWaitTimeout) {355  using namespace llvm::sys;356 357  if (getenv("LLVM_PROGRAM_TEST_TIMEOUT")) {358    sleep_for(/*seconds*/ 10);359    exit(0);360  }361 362  std::string Executable =363      sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);364  StringRef argv[] = {365      Executable, "--gtest_filter=ProgramEnvTest.TestExecuteAndWaitTimeout"};366 367  // Add LLVM_PROGRAM_TEST_TIMEOUT to the environment of the child.368 addEnvVar("LLVM_PROGRAM_TEST_TIMEOUT=1");369 370  std::string Error;371  bool ExecutionFailed;372  int RetCode =373      ExecuteAndWait(Executable, argv, getEnviron(), {}, /*SecondsToWait=*/1,374                     /*MemoryLimit*/ 0, &Error, &ExecutionFailed);375  ASSERT_EQ(-2, RetCode);376}377 378TEST_F(ProgramEnvTest, TestExecuteNoWaitTimeoutPolling) {379  using namespace llvm::sys;380 381  if (getenv("LLVM_PROGRAM_TEST_TIMEOUT")) {382    sleep_for(/*seconds*/ 5);383    exit(0);384  }385 386  std::string Executable =387      sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);388  StringRef argv[] = {389      Executable,390      "--gtest_filter=ProgramEnvTest.TestExecuteNoWaitTimeoutPolling"};391 392  // Add LLVM_PROGRAM_TEST_TIMEOUT to the environment of the child.393  addEnvVar("LLVM_PROGRAM_TEST_TIMEOUT=1");394 395  std::string Error;396  bool ExecutionFailed;397  ProcessInfo PI0 = ExecuteNoWait(Executable, argv, getEnviron(),398                                  /*Redirects=*/{}, /*MemoryLimit=*/0, &Error,399                                  &ExecutionFailed);400  ASSERT_FALSE(ExecutionFailed) << Error;401  ASSERT_NE(PI0.Pid, ProcessInfo::InvalidPid) << "Invalid process id";402 403  // Check that we don't kill the process with a non-0 SecondsToWait if Polling.404  unsigned LoopCount = 0;405  ProcessInfo WaitResult;406  do {407    ++LoopCount;408    WaitResult = llvm::sys::Wait(PI0, /*SecondsToWait=*/1, &Error,409                                 /*ProcStats=*/nullptr,410                                 /*Polling=*/true);411    ASSERT_TRUE(Error.empty()) << Error;412  } while (WaitResult.Pid != PI0.Pid);413 414  ASSERT_GT(LoopCount, 1u) << "LoopCount should be >1";415}416 417TEST(ProgramTest, TestExecuteNegative) {418  std::string Executable = "i_dont_exist";419  StringRef argv[] = {Executable};420 421  {422    std::string Error;423    bool ExecutionFailed;424    int RetCode = ExecuteAndWait(Executable, argv, std::nullopt, {}, 0, 0,425                                 &Error, &ExecutionFailed);426 427    EXPECT_LT(RetCode, 0) << "On error ExecuteAndWait should return 0 or "428                             "positive value indicating the result code";429    EXPECT_FALSE(Error.empty());430 431    // Note ExecutionFailed may or may not be false. When using fork, the error432    // is produced on the wait for the child, not the execution point.433  }434 435  {436    std::string Error;437    bool ExecutionFailed;438    ProcessInfo PI = ExecuteNoWait(Executable, argv, std::nullopt, {}, 0,439                                   &Error, &ExecutionFailed);440 441    if (ExecutionFailed) {442      EXPECT_EQ(PI.Pid, ProcessInfo::InvalidPid)443          << "On error ExecuteNoWait should return an invalid ProcessInfo";444      EXPECT_FALSE(Error.empty());445    } else {446      std::string WaitErrMsg;447      EXPECT_NE(PI.Pid, ProcessInfo::InvalidPid);448      ProcessInfo WaitPI = Wait(PI, std::nullopt, &WaitErrMsg);449      EXPECT_EQ(WaitPI.Pid, PI.Pid);450      EXPECT_LT(WaitPI.ReturnCode, 0);451      EXPECT_FALSE(WaitErrMsg.empty());452    }453  }454 455}456 457#ifdef _WIN32458const char utf16le_text[] =459    "\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61\x00";460const char utf16be_text[] =461    "\x00\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61";462#endif463const char utf8_text[] = "\x6c\x69\x6e\x67\xc3\xbc\x69\xc3\xa7\x61";464 465TEST(ProgramTest, TestWriteWithSystemEncoding) {466  SmallString<128> TestDirectory;467  ASSERT_NO_ERROR(fs::createUniqueDirectory("program-test", TestDirectory));468  errs() << "Test Directory: " << TestDirectory << '\n';469  errs().flush();470  SmallString<128> file_pathname(TestDirectory);471  path::append(file_pathname, "international-file.txt");472  // Only on Windows we should encode in UTF16. For other systems, use UTF8473  ASSERT_NO_ERROR(sys::writeFileWithEncoding(file_pathname.c_str(), utf8_text,474                                             sys::WEM_UTF16));475  int fd = 0;476  ASSERT_NO_ERROR(fs::openFileForRead(file_pathname.c_str(), fd));477#if defined(_WIN32)478  char buf[18];479  ASSERT_EQ(::read(fd, buf, 18), 18);480  const char *utf16_text;481  if (strncmp(buf, "\xfe\xff", 2) == 0) { // UTF16-BE482    utf16_text = utf16be_text;483  } else if (strncmp(buf, "\xff\xfe", 2) == 0) { // UTF16-LE484    utf16_text = utf16le_text;485  } else {486    FAIL() << "Invalid BOM in UTF-16 file";487  }488  ASSERT_EQ(strncmp(&buf[2], utf16_text, 16), 0);489#else490  char buf[10];491  ASSERT_EQ(::read(fd, buf, 10), 10);492  ASSERT_EQ(strncmp(buf, utf8_text, 10), 0);493#endif494  ::close(fd);495  ASSERT_NO_ERROR(fs::remove(file_pathname.str()));496  ASSERT_NO_ERROR(fs::remove(TestDirectory.str()));497}498 499TEST_F(ProgramEnvTest, TestExecuteAndWaitStatistics) {500  using namespace llvm::sys;501 502  if (getenv("LLVM_PROGRAM_TEST_STATISTICS"))503    exit(0);504 505  std::string Executable =506      sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);507  StringRef argv[] = {508      Executable, "--gtest_filter=ProgramEnvTest.TestExecuteAndWaitStatistics"};509 510  // Add LLVM_PROGRAM_TEST_STATISTICS to the environment of the child.511  addEnvVar("LLVM_PROGRAM_TEST_STATISTICS=1");512 513  std::string Error;514  bool ExecutionFailed;515  std::optional<ProcessStatistics> ProcStat;516  int RetCode = ExecuteAndWait(Executable, argv, getEnviron(), {}, 0, 0, &Error,517                               &ExecutionFailed, &ProcStat);518  ASSERT_EQ(0, RetCode);519  ASSERT_TRUE(ProcStat);520  ASSERT_GE(ProcStat->UserTime, std::chrono::microseconds(0));521  ASSERT_GE(ProcStat->TotalTime, ProcStat->UserTime);522}523 524TEST_F(ProgramEnvTest, TestLockFile) {525  using namespace llvm::sys;526 527  if (const char *LockedFile = getenv("LLVM_PROGRAM_TEST_LOCKED_FILE")) {528    // Child process.529    int FD2;530    ASSERT_NO_ERROR(fs::openFileForReadWrite(LockedFile, FD2,531                                             fs::CD_OpenExisting, fs::OF_None));532 533    std::error_code ErrC = fs::tryLockFile(FD2, std::chrono::seconds(5));534    ASSERT_NO_ERROR(ErrC);535    ASSERT_NO_ERROR(fs::unlockFile(FD2));536    close(FD2);537    exit(0);538  }539 540  // Create file that will be locked.541  SmallString<64> LockedFile;542  int FD1;543  ASSERT_NO_ERROR(544      fs::createTemporaryFile("TestLockFile", "temp", FD1, LockedFile));545 546  std::string Executable =547      sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);548  StringRef argv[] = {Executable, "--gtest_filter=ProgramEnvTest.TestLockFile"};549 550  // Add LLVM_PROGRAM_TEST_LOCKED_FILE to the environment of the child.551  std::string EnvVar = "LLVM_PROGRAM_TEST_LOCKED_FILE=";552  EnvVar += LockedFile.str();553  addEnvVar(EnvVar);554 555  // Lock the file.556  ASSERT_NO_ERROR(fs::tryLockFile(FD1));557 558  std::string Error;559  bool ExecutionFailed;560  ProcessInfo PI2 = ExecuteNoWait(Executable, argv, getEnviron(), {}, 0, &Error,561                                  &ExecutionFailed);562  ASSERT_FALSE(ExecutionFailed) << Error;563  ASSERT_TRUE(Error.empty());564  ASSERT_NE(PI2.Pid, ProcessInfo::InvalidPid) << "Invalid process id";565 566  // Wait some time to give the child process a chance to start.567  std::this_thread::sleep_for(std::chrono::milliseconds(100));568 569  ASSERT_NO_ERROR(fs::unlockFile(FD1));570  ProcessInfo WaitResult = llvm::sys::Wait(PI2, /*SecondsToWait=*/5, &Error);571  ASSERT_TRUE(Error.empty());572  ASSERT_EQ(0, WaitResult.ReturnCode);573  ASSERT_EQ(WaitResult.Pid, PI2.Pid);574  sys::fs::remove(LockedFile);575}576 577TEST_F(ProgramEnvTest, TestLockFileExclusive) {578  using namespace llvm::sys;579  using namespace std::chrono_literals;580 581  if (const char *LockedFile = getenv("LLVM_PROGRAM_TEST_LOCKED_FILE")) {582    // Child process.583    int FD2;584    ASSERT_NO_ERROR(fs::openFileForReadWrite(LockedFile, FD2,585                                             fs::CD_OpenExisting, fs::OF_None));586 587    // File should currently be non-exclusive locked by the main process, thus588    // trying to acquire exclusive lock will fail and trying to acquire589    // non-exclusive will succeed.590    EXPECT_TRUE(591        fs::tryLockFile(FD2, std::chrono::seconds(0), fs::LockKind::Exclusive));592 593    EXPECT_FALSE(594        fs::tryLockFile(FD2, std::chrono::seconds(0), fs::LockKind::Shared));595 596    close(FD2);597    // Write a file to indicate just finished.598    std::string FinishFile = std::string(LockedFile) + "-finished";599    int FD3;600    ASSERT_NO_ERROR(fs::openFileForReadWrite(FinishFile, FD3, fs::CD_CreateNew,601                                             fs::OF_None));602    close(FD3);603    exit(0);604  }605 606  // Create file that will be locked.607  SmallString<64> LockedFile;608  int FD1;609  ASSERT_NO_ERROR(610      fs::createUniqueDirectory("TestLockFileExclusive", LockedFile));611  sys::path::append(LockedFile, "file");612  ASSERT_NO_ERROR(613      fs::openFileForReadWrite(LockedFile, FD1, fs::CD_CreateNew, fs::OF_None));614 615  std::string Executable =616      sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);617  StringRef argv[] = {Executable,618                      "--gtest_filter=ProgramEnvTest.TestLockFileExclusive"};619 620  // Add LLVM_PROGRAM_TEST_LOCKED_FILE to the environment of the child.621  std::string EnvVar = "LLVM_PROGRAM_TEST_LOCKED_FILE=";622  EnvVar += LockedFile.str();623  addEnvVar(EnvVar);624 625  // Lock the file.626  ASSERT_NO_ERROR(627      fs::tryLockFile(FD1, std::chrono::seconds(0), fs::LockKind::Exclusive));628 629  std::string Error;630  bool ExecutionFailed;631  ProcessInfo PI2 = ExecuteNoWait(Executable, argv, getEnviron(), {}, 0, &Error,632                                  &ExecutionFailed);633  ASSERT_FALSE(ExecutionFailed) << Error;634  ASSERT_TRUE(Error.empty());635  ASSERT_NE(PI2.Pid, ProcessInfo::InvalidPid) << "Invalid process id";636 637  std::string FinishFile = std::string(LockedFile) + "-finished";638  // Wait till child process writes the file to indicate the job finished.639  bool Finished = false;640  ExponentialBackoff Backoff(5s); // timeout 5s.641  do {642    if (fs::exists(FinishFile)) {643      Finished = true;644      break;645    }646  } while (Backoff.waitForNextAttempt());647 648  ASSERT_TRUE(Finished);649  ASSERT_NO_ERROR(fs::unlockFile(FD1));650  ProcessInfo WaitResult = llvm::sys::Wait(PI2, /*SecondsToWait=*/1, &Error);651  ASSERT_TRUE(Error.empty());652  ASSERT_EQ(0, WaitResult.ReturnCode);653  ASSERT_EQ(WaitResult.Pid, PI2.Pid);654  sys::fs::remove(LockedFile);655  sys::fs::remove(FinishFile);656  sys::fs::remove_directories(sys::path::parent_path(LockedFile));657}658 659TEST_F(ProgramEnvTest, TestExecuteWithNoStacktraceHandler) {660  using namespace llvm::sys;661 662  if (getenv("LLVM_PROGRAM_TEST_NO_STACKTRACE_HANDLER")) {663    sys::PrintStackTrace(errs());664    exit(0);665  }666 667  std::string Executable =668      sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);669  StringRef argv[] = {670      Executable,671      "--gtest_filter=ProgramEnvTest.TestExecuteWithNoStacktraceHandler"};672 673  addEnvVar("LLVM_PROGRAM_TEST_NO_STACKTRACE_HANDLER=1");674 675  std::string Error;676  bool ExecutionFailed;677  int RetCode = ExecuteAndWait(Executable, argv, getEnviron(), {}, 0, 0, &Error,678                               &ExecutionFailed);679  EXPECT_FALSE(ExecutionFailed) << Error;680  ASSERT_EQ(0, RetCode);681}682 683TEST_F(ProgramEnvTest, TestExecuteEmptyEnvironment) {684  using namespace llvm::sys;685 686  std::string Executable =687      sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);688  StringRef argv[] = {689      Executable,690      "--gtest_filter=" // A null invocation to avoid infinite recursion691  };692 693  std::string Error;694  bool ExecutionFailed;695  int RetCode = ExecuteAndWait(Executable, argv, ArrayRef<StringRef>{}, {}, 0,696                               0, &Error, &ExecutionFailed);697  EXPECT_FALSE(ExecutionFailed) << Error;698#ifndef __MINGW32__699  // When running with an empty environment, the child process doesn't in herit700  // the PATH variable. On MinGW, it is common for executables to require a701  // shared libstdc++ or libc++ DLL, which may be in PATH but not in the702  // directory of SupportTests.exe - leading to STATUS_DLL_NOT_FOUND errors.703  // Therefore, waive this failure in MinGW environments.704  ASSERT_EQ(0, RetCode);705#endif706}707 708} // end anonymous namespace709