1//===- unittest/Support/ProgramTest.cpp -----------------------------------===//
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 "llvm/Support/CommandLine.h"
11#include "llvm/Support/FileSystem.h"
12#include "llvm/Support/Path.h"
13#include "llvm/Support/Program.h"
14#include "gtest/gtest.h"
15#include <stdlib.h>
16#if defined(__APPLE__)
17# include <crt_externs.h>
18#elif !defined(_MSC_VER)
19// Forward declare environ in case it's not provided by stdlib.h.
20extern char **environ;
21#endif
22
23#if defined(LLVM_ON_UNIX)
24#include <unistd.h>
25void sleep_for(unsigned int seconds) {
26  sleep(seconds);
27}
28#elif defined(LLVM_ON_WIN32)
29#include <windows.h>
30void sleep_for(unsigned int seconds) {
31  Sleep(seconds * 1000);
32}
33#else
34#error sleep_for is not implemented on your platform.
35#endif
36
37#define ASSERT_NO_ERROR(x)                                                     \
38  if (std::error_code ASSERT_NO_ERROR_ec = x) {                                \
39    SmallString<128> MessageStorage;                                           \
40    raw_svector_ostream Message(MessageStorage);                               \
41    Message << #x ": did not return errc::success.\n"                          \
42            << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n"          \
43            << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n";      \
44    GTEST_FATAL_FAILURE_(MessageStorage.c_str());                              \
45  } else {                                                                     \
46  }
47// From TestMain.cpp.
48extern const char *TestMainArgv0;
49
50namespace {
51
52using namespace llvm;
53using namespace sys;
54
55static cl::opt<std::string>
56ProgramTestStringArg1("program-test-string-arg1");
57static cl::opt<std::string>
58ProgramTestStringArg2("program-test-string-arg2");
59
60static void CopyEnvironment(std::vector<const char *> &out) {
61#ifdef __APPLE__
62  char **envp = *_NSGetEnviron();
63#else
64  // environ seems to work for Windows and most other Unices.
65  char **envp = environ;
66#endif
67  while (*envp != nullptr) {
68    out.push_back(*envp);
69    ++envp;
70  }
71}
72
73#ifdef LLVM_ON_WIN32
74TEST(ProgramTest, CreateProcessLongPath) {
75  if (getenv("LLVM_PROGRAM_TEST_LONG_PATH"))
76    exit(0);
77
78  // getMainExecutable returns an absolute path; prepend the long-path prefix.
79  std::string MyAbsExe =
80      sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
81  std::string MyExe;
82  if (!StringRef(MyAbsExe).startswith("\\\\?\\"))
83    MyExe.append("\\\\?\\");
84  MyExe.append(MyAbsExe);
85
86  const char *ArgV[] = {
87    MyExe.c_str(),
88    "--gtest_filter=ProgramTest.CreateProcessLongPath",
89    nullptr
90  };
91
92  // Add LLVM_PROGRAM_TEST_LONG_PATH to the environment of the child.
93  std::vector<const char *> EnvP;
94  CopyEnvironment(EnvP);
95  EnvP.push_back("LLVM_PROGRAM_TEST_LONG_PATH=1");
96  EnvP.push_back(nullptr);
97
98  // Redirect stdout to a long path.
99  SmallString<128> TestDirectory;
100  ASSERT_NO_ERROR(
101    fs::createUniqueDirectory("program-redirect-test", TestDirectory));
102  SmallString<256> LongPath(TestDirectory);
103  LongPath.push_back('\\');
104  // MAX_PATH = 260
105  LongPath.append(260 - TestDirectory.size(), 'a');
106  StringRef LongPathRef(LongPath);
107
108  std::string Error;
109  bool ExecutionFailed;
110  const StringRef *Redirects[] = { nullptr, &LongPathRef, nullptr };
111  int RC = ExecuteAndWait(MyExe, ArgV, &EnvP[0], Redirects,
112    /*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &Error,
113    &ExecutionFailed);
114  EXPECT_FALSE(ExecutionFailed) << Error;
115  EXPECT_EQ(0, RC);
116
117  // Remove the long stdout.
118  ASSERT_NO_ERROR(fs::remove(Twine(LongPath)));
119  ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory)));
120}
121#endif
122
123TEST(ProgramTest, CreateProcessTrailingSlash) {
124  if (getenv("LLVM_PROGRAM_TEST_CHILD")) {
125    if (ProgramTestStringArg1 == "has\\\\ trailing\\" &&
126        ProgramTestStringArg2 == "has\\\\ trailing\\") {
127      exit(0);  // Success!  The arguments were passed and parsed.
128    }
129    exit(1);
130  }
131
132  std::string my_exe =
133      sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
134  const char *argv[] = {
135    my_exe.c_str(),
136    "--gtest_filter=ProgramTest.CreateProcessTrailingSlash",
137    "-program-test-string-arg1", "has\\\\ trailing\\",
138    "-program-test-string-arg2", "has\\\\ trailing\\",
139    nullptr
140  };
141
142  // Add LLVM_PROGRAM_TEST_CHILD to the environment of the child.
143  std::vector<const char *> envp;
144  CopyEnvironment(envp);
145  envp.push_back("LLVM_PROGRAM_TEST_CHILD=1");
146  envp.push_back(nullptr);
147
148  std::string error;
149  bool ExecutionFailed;
150  // Redirect stdout and stdin to NUL, but let stderr through.
151#ifdef LLVM_ON_WIN32
152  StringRef nul("NUL");
153#else
154  StringRef nul("/dev/null");
155#endif
156  const StringRef *redirects[] = { &nul, &nul, nullptr };
157  int rc = ExecuteAndWait(my_exe, argv, &envp[0], redirects,
158                          /*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &error,
159                          &ExecutionFailed);
160  EXPECT_FALSE(ExecutionFailed) << error;
161  EXPECT_EQ(0, rc);
162}
163
164TEST(ProgramTest, TestExecuteNoWait) {
165  using namespace llvm::sys;
166
167  if (getenv("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT")) {
168    sleep_for(/*seconds*/ 1);
169    exit(0);
170  }
171
172  std::string Executable =
173      sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
174  const char *argv[] = {
175    Executable.c_str(),
176    "--gtest_filter=ProgramTest.TestExecuteNoWait",
177    nullptr
178  };
179
180  // Add LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT to the environment of the child.
181  std::vector<const char *> envp;
182  CopyEnvironment(envp);
183  envp.push_back("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT=1");
184  envp.push_back(nullptr);
185
186  std::string Error;
187  bool ExecutionFailed;
188  ProcessInfo PI1 = ExecuteNoWait(Executable, argv, &envp[0], nullptr, 0,
189                                  &Error, &ExecutionFailed);
190  ASSERT_FALSE(ExecutionFailed) << Error;
191  ASSERT_NE(PI1.Pid, 0) << "Invalid process id";
192
193  unsigned LoopCount = 0;
194
195  // Test that Wait() with WaitUntilTerminates=true works. In this case,
196  // LoopCount should only be incremented once.
197  while (true) {
198    ++LoopCount;
199    ProcessInfo WaitResult = Wait(PI1, 0, true, &Error);
200    ASSERT_TRUE(Error.empty());
201    if (WaitResult.Pid == PI1.Pid)
202      break;
203  }
204
205  EXPECT_EQ(LoopCount, 1u) << "LoopCount should be 1";
206
207  ProcessInfo PI2 = ExecuteNoWait(Executable, argv, &envp[0], nullptr, 0,
208                                  &Error, &ExecutionFailed);
209  ASSERT_FALSE(ExecutionFailed) << Error;
210  ASSERT_NE(PI2.Pid, 0) << "Invalid process id";
211
212  // Test that Wait() with SecondsToWait=0 performs a non-blocking wait. In this
213  // cse, LoopCount should be greater than 1 (more than one increment occurs).
214  while (true) {
215    ++LoopCount;
216    ProcessInfo WaitResult = Wait(PI2, 0, false, &Error);
217    ASSERT_TRUE(Error.empty());
218    if (WaitResult.Pid == PI2.Pid)
219      break;
220  }
221
222  ASSERT_GT(LoopCount, 1u) << "LoopCount should be >1";
223}
224
225TEST(ProgramTest, TestExecuteAndWaitTimeout) {
226  using namespace llvm::sys;
227
228  if (getenv("LLVM_PROGRAM_TEST_TIMEOUT")) {
229    sleep_for(/*seconds*/ 10);
230    exit(0);
231  }
232
233  std::string Executable =
234      sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
235  const char *argv[] = {
236    Executable.c_str(),
237    "--gtest_filter=ProgramTest.TestExecuteAndWaitTimeout",
238    nullptr
239  };
240
241  // Add LLVM_PROGRAM_TEST_TIMEOUT to the environment of the child.
242  std::vector<const char *> envp;
243  CopyEnvironment(envp);
244  envp.push_back("LLVM_PROGRAM_TEST_TIMEOUT=1");
245  envp.push_back(nullptr);
246
247  std::string Error;
248  bool ExecutionFailed;
249  int RetCode =
250      ExecuteAndWait(Executable, argv, &envp[0], nullptr, /*secondsToWait=*/1, 0,
251                     &Error, &ExecutionFailed);
252  ASSERT_EQ(-2, RetCode);
253}
254
255TEST(ProgramTest, TestExecuteNegative) {
256  std::string Executable = "i_dont_exist";
257  const char *argv[] = { Executable.c_str(), nullptr };
258
259  {
260    std::string Error;
261    bool ExecutionFailed;
262    int RetCode = ExecuteAndWait(Executable, argv, nullptr, nullptr, 0, 0,
263                                 &Error, &ExecutionFailed);
264    ASSERT_TRUE(RetCode < 0) << "On error ExecuteAndWait should return 0 or "
265                                "positive value indicating the result code";
266    ASSERT_TRUE(ExecutionFailed);
267    ASSERT_FALSE(Error.empty());
268  }
269
270  {
271    std::string Error;
272    bool ExecutionFailed;
273    ProcessInfo PI = ExecuteNoWait(Executable, argv, nullptr, nullptr, 0,
274                                   &Error, &ExecutionFailed);
275    ASSERT_EQ(PI.Pid, 0)
276        << "On error ExecuteNoWait should return an invalid ProcessInfo";
277    ASSERT_TRUE(ExecutionFailed);
278    ASSERT_FALSE(Error.empty());
279  }
280
281}
282
283#ifdef LLVM_ON_WIN32
284const char utf16le_text[] =
285    "\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61\x00";
286const char utf16be_text[] =
287    "\x00\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61";
288#endif
289const char utf8_text[] = "\x6c\x69\x6e\x67\xc3\xbc\x69\xc3\xa7\x61";
290
291TEST(ProgramTest, TestWriteWithSystemEncoding) {
292  SmallString<128> TestDirectory;
293  ASSERT_NO_ERROR(fs::createUniqueDirectory("program-test", TestDirectory));
294  errs() << "Test Directory: " << TestDirectory << '\n';
295  errs().flush();
296  SmallString<128> file_pathname(TestDirectory);
297  path::append(file_pathname, "international-file.txt");
298  // Only on Windows we should encode in UTF16. For other systems, use UTF8
299  ASSERT_NO_ERROR(sys::writeFileWithEncoding(file_pathname.c_str(), utf8_text,
300                                             sys::WEM_UTF16));
301  int fd = 0;
302  ASSERT_NO_ERROR(fs::openFileForRead(file_pathname.c_str(), fd));
303#if defined(LLVM_ON_WIN32)
304  char buf[18];
305  ASSERT_EQ(::read(fd, buf, 18), 18);
306  if (strncmp(buf, "\xfe\xff", 2) == 0) { // UTF16-BE
307    ASSERT_EQ(strncmp(&buf[2], utf16be_text, 16), 0);
308  } else if (strncmp(buf, "\xff\xfe", 2) == 0) { // UTF16-LE
309    ASSERT_EQ(strncmp(&buf[2], utf16le_text, 16), 0);
310  } else {
311    FAIL() << "Invalid BOM in UTF-16 file";
312  }
313#else
314  char buf[10];
315  ASSERT_EQ(::read(fd, buf, 10), 10);
316  ASSERT_EQ(strncmp(buf, utf8_text, 10), 0);
317#endif
318  ::close(fd);
319  ASSERT_NO_ERROR(fs::remove(file_pathname.str()));
320  ASSERT_NO_ERROR(fs::remove(TestDirectory.str()));
321}
322
323} // end anonymous namespace
324