xref: /llvm-project/llvm/unittests/Support/ProgramTest.cpp (revision b7578f9d5a465ae1c061ccfbe3cf2a5265785f87)
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-exception
6 //
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/FileSystem.h"
14 #include "llvm/Support/Path.h"
15 #include "gtest/gtest.h"
16 #include <stdlib.h>
17 #include <thread>
18 #if defined(__APPLE__)
19 # include <crt_externs.h>
20 #elif !defined(_MSC_VER)
21 // Forward declare environ in case it's not provided by stdlib.h.
22 extern char **environ;
23 #endif
24 
25 #if defined(LLVM_ON_UNIX)
26 #include <unistd.h>
27 void sleep_for(unsigned int seconds) {
28   sleep(seconds);
29 }
30 #elif defined(_WIN32)
31 #include <windows.h>
32 void sleep_for(unsigned int seconds) {
33   Sleep(seconds * 1000);
34 }
35 #else
36 #error sleep_for is not implemented on your platform.
37 #endif
38 
39 #define ASSERT_NO_ERROR(x)                                                     \
40   if (std::error_code ASSERT_NO_ERROR_ec = x) {                                \
41     SmallString<128> MessageStorage;                                           \
42     raw_svector_ostream Message(MessageStorage);                               \
43     Message << #x ": did not return errc::success.\n"                          \
44             << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n"          \
45             << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n";      \
46     GTEST_FATAL_FAILURE_(MessageStorage.c_str());                              \
47   } else {                                                                     \
48   }
49 // From TestMain.cpp.
50 extern const char *TestMainArgv0;
51 
52 namespace {
53 
54 using namespace llvm;
55 using namespace sys;
56 
57 static cl::opt<std::string>
58 ProgramTestStringArg1("program-test-string-arg1");
59 static cl::opt<std::string>
60 ProgramTestStringArg2("program-test-string-arg2");
61 
62 class ProgramEnvTest : public testing::Test {
63   std::vector<StringRef> EnvTable;
64   std::vector<std::string> EnvStorage;
65 
66 protected:
67   void SetUp() override {
68     auto EnvP = [] {
69 #if defined(_WIN32)
70       _wgetenv(L"TMP"); // Populate _wenviron, initially is null
71       return _wenviron;
72 #elif defined(__APPLE__)
73       return *_NSGetEnviron();
74 #else
75       return environ;
76 #endif
77     }();
78     ASSERT_TRUE(EnvP);
79 
80     auto prepareEnvVar = [this](decltype(*EnvP) Var) -> StringRef {
81 #if defined(_WIN32)
82       // On Windows convert UTF16 encoded variable to UTF8
83       auto Len = wcslen(Var);
84       ArrayRef<char> Ref{reinterpret_cast<char const *>(Var),
85                          Len * sizeof(*Var)};
86       EnvStorage.emplace_back();
87       auto convStatus = convertUTF16ToUTF8String(Ref, EnvStorage.back());
88       EXPECT_TRUE(convStatus);
89       return EnvStorage.back();
90 #else
91       (void)this;
92       return StringRef(Var);
93 #endif
94     };
95 
96     while (*EnvP != nullptr) {
97       EnvTable.emplace_back(prepareEnvVar(*EnvP));
98       ++EnvP;
99     }
100   }
101 
102   void TearDown() override {
103     EnvTable.clear();
104     EnvStorage.clear();
105   }
106 
107   void addEnvVar(StringRef Var) { EnvTable.emplace_back(Var); }
108 
109   ArrayRef<StringRef> getEnviron() const { return EnvTable; }
110 };
111 
112 #ifdef _WIN32
113 TEST_F(ProgramEnvTest, CreateProcessLongPath) {
114   if (getenv("LLVM_PROGRAM_TEST_LONG_PATH"))
115     exit(0);
116 
117   // getMainExecutable returns an absolute path; prepend the long-path prefix.
118   std::string MyAbsExe =
119       sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
120   std::string MyExe;
121   if (!StringRef(MyAbsExe).startswith("\\\\?\\"))
122     MyExe.append("\\\\?\\");
123   MyExe.append(MyAbsExe);
124 
125   StringRef ArgV[] = {MyExe,
126                       "--gtest_filter=ProgramEnvTest.CreateProcessLongPath"};
127 
128   // Add LLVM_PROGRAM_TEST_LONG_PATH to the environment of the child.
129   addEnvVar("LLVM_PROGRAM_TEST_LONG_PATH=1");
130 
131   // Redirect stdout to a long path.
132   SmallString<128> TestDirectory;
133   ASSERT_NO_ERROR(
134     fs::createUniqueDirectory("program-redirect-test", TestDirectory));
135   SmallString<256> LongPath(TestDirectory);
136   LongPath.push_back('\\');
137   // MAX_PATH = 260
138   LongPath.append(260 - TestDirectory.size(), 'a');
139 
140   std::string Error;
141   bool ExecutionFailed;
142   Optional<StringRef> Redirects[] = {None, LongPath.str(), None};
143   int RC = ExecuteAndWait(MyExe, ArgV, getEnviron(), Redirects,
144     /*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &Error,
145     &ExecutionFailed);
146   EXPECT_FALSE(ExecutionFailed) << Error;
147   EXPECT_EQ(0, RC);
148 
149   // Remove the long stdout.
150   ASSERT_NO_ERROR(fs::remove(Twine(LongPath)));
151   ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory)));
152 }
153 #endif
154 
155 TEST_F(ProgramEnvTest, CreateProcessTrailingSlash) {
156   if (getenv("LLVM_PROGRAM_TEST_CHILD")) {
157     if (ProgramTestStringArg1 == "has\\\\ trailing\\" &&
158         ProgramTestStringArg2 == "has\\\\ trailing\\") {
159       exit(0);  // Success!  The arguments were passed and parsed.
160     }
161     exit(1);
162   }
163 
164   std::string my_exe =
165       sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
166   StringRef argv[] = {
167       my_exe,
168       "--gtest_filter=ProgramEnvTest.CreateProcessTrailingSlash",
169       "-program-test-string-arg1",
170       "has\\\\ trailing\\",
171       "-program-test-string-arg2",
172       "has\\\\ trailing\\"};
173 
174   // Add LLVM_PROGRAM_TEST_CHILD to the environment of the child.
175   addEnvVar("LLVM_PROGRAM_TEST_CHILD=1");
176 
177   std::string error;
178   bool ExecutionFailed;
179   // Redirect stdout and stdin to NUL, but let stderr through.
180 #ifdef _WIN32
181   StringRef nul("NUL");
182 #else
183   StringRef nul("/dev/null");
184 #endif
185   Optional<StringRef> redirects[] = { nul, nul, None };
186   int rc = ExecuteAndWait(my_exe, argv, getEnviron(), redirects,
187                           /*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &error,
188                           &ExecutionFailed);
189   EXPECT_FALSE(ExecutionFailed) << error;
190   EXPECT_EQ(0, rc);
191 }
192 
193 TEST_F(ProgramEnvTest, TestExecuteNoWait) {
194   using namespace llvm::sys;
195 
196   if (getenv("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT")) {
197     sleep_for(/*seconds*/ 1);
198     exit(0);
199   }
200 
201   std::string Executable =
202       sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
203   StringRef argv[] = {Executable,
204                       "--gtest_filter=ProgramEnvTest.TestExecuteNoWait"};
205 
206   // Add LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT to the environment of the child.
207   addEnvVar("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT=1");
208 
209   std::string Error;
210   bool ExecutionFailed;
211   ProcessInfo PI1 = ExecuteNoWait(Executable, argv, getEnviron(), {}, 0, &Error,
212                                   &ExecutionFailed);
213   ASSERT_FALSE(ExecutionFailed) << Error;
214   ASSERT_NE(PI1.Pid, ProcessInfo::InvalidPid) << "Invalid process id";
215 
216   unsigned LoopCount = 0;
217 
218   // Test that Wait() with WaitUntilTerminates=true works. In this case,
219   // LoopCount should only be incremented once.
220   while (true) {
221     ++LoopCount;
222     ProcessInfo WaitResult = llvm::sys::Wait(PI1, 0, true, &Error);
223     ASSERT_TRUE(Error.empty());
224     if (WaitResult.Pid == PI1.Pid)
225       break;
226   }
227 
228   EXPECT_EQ(LoopCount, 1u) << "LoopCount should be 1";
229 
230   ProcessInfo PI2 = ExecuteNoWait(Executable, argv, getEnviron(), {}, 0, &Error,
231                                   &ExecutionFailed);
232   ASSERT_FALSE(ExecutionFailed) << Error;
233   ASSERT_NE(PI2.Pid, ProcessInfo::InvalidPid) << "Invalid process id";
234 
235   // Test that Wait() with SecondsToWait=0 performs a non-blocking wait. In this
236   // cse, LoopCount should be greater than 1 (more than one increment occurs).
237   while (true) {
238     ++LoopCount;
239     ProcessInfo WaitResult = llvm::sys::Wait(PI2, 0, false, &Error);
240     ASSERT_TRUE(Error.empty());
241     if (WaitResult.Pid == PI2.Pid)
242       break;
243   }
244 
245   ASSERT_GT(LoopCount, 1u) << "LoopCount should be >1";
246 }
247 
248 TEST_F(ProgramEnvTest, TestExecuteAndWaitTimeout) {
249   using namespace llvm::sys;
250 
251   if (getenv("LLVM_PROGRAM_TEST_TIMEOUT")) {
252     sleep_for(/*seconds*/ 10);
253     exit(0);
254   }
255 
256   std::string Executable =
257       sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
258   StringRef argv[] = {
259       Executable, "--gtest_filter=ProgramEnvTest.TestExecuteAndWaitTimeout"};
260 
261   // Add LLVM_PROGRAM_TEST_TIMEOUT to the environment of the child.
262  addEnvVar("LLVM_PROGRAM_TEST_TIMEOUT=1");
263 
264   std::string Error;
265   bool ExecutionFailed;
266   int RetCode =
267       ExecuteAndWait(Executable, argv, getEnviron(), {}, /*secondsToWait=*/1, 0,
268                      &Error, &ExecutionFailed);
269   ASSERT_EQ(-2, RetCode);
270 }
271 
272 TEST(ProgramTest, TestExecuteNegative) {
273   std::string Executable = "i_dont_exist";
274   StringRef argv[] = {Executable};
275 
276   {
277     std::string Error;
278     bool ExecutionFailed;
279     int RetCode = ExecuteAndWait(Executable, argv, llvm::None, {}, 0, 0, &Error,
280                                  &ExecutionFailed);
281     ASSERT_TRUE(RetCode < 0) << "On error ExecuteAndWait should return 0 or "
282                                 "positive value indicating the result code";
283     ASSERT_TRUE(ExecutionFailed);
284     ASSERT_FALSE(Error.empty());
285   }
286 
287   {
288     std::string Error;
289     bool ExecutionFailed;
290     ProcessInfo PI = ExecuteNoWait(Executable, argv, llvm::None, {}, 0, &Error,
291                                    &ExecutionFailed);
292     ASSERT_EQ(PI.Pid, ProcessInfo::InvalidPid)
293         << "On error ExecuteNoWait should return an invalid ProcessInfo";
294     ASSERT_TRUE(ExecutionFailed);
295     ASSERT_FALSE(Error.empty());
296   }
297 
298 }
299 
300 #ifdef _WIN32
301 const char utf16le_text[] =
302     "\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61\x00";
303 const char utf16be_text[] =
304     "\x00\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61";
305 #endif
306 const char utf8_text[] = "\x6c\x69\x6e\x67\xc3\xbc\x69\xc3\xa7\x61";
307 
308 TEST(ProgramTest, TestWriteWithSystemEncoding) {
309   SmallString<128> TestDirectory;
310   ASSERT_NO_ERROR(fs::createUniqueDirectory("program-test", TestDirectory));
311   errs() << "Test Directory: " << TestDirectory << '\n';
312   errs().flush();
313   SmallString<128> file_pathname(TestDirectory);
314   path::append(file_pathname, "international-file.txt");
315   // Only on Windows we should encode in UTF16. For other systems, use UTF8
316   ASSERT_NO_ERROR(sys::writeFileWithEncoding(file_pathname.c_str(), utf8_text,
317                                              sys::WEM_UTF16));
318   int fd = 0;
319   ASSERT_NO_ERROR(fs::openFileForRead(file_pathname.c_str(), fd));
320 #if defined(_WIN32)
321   char buf[18];
322   ASSERT_EQ(::read(fd, buf, 18), 18);
323   const char *utf16_text;
324   if (strncmp(buf, "\xfe\xff", 2) == 0) { // UTF16-BE
325     utf16_text = utf16be_text;
326   } else if (strncmp(buf, "\xff\xfe", 2) == 0) { // UTF16-LE
327     utf16_text = utf16le_text;
328   } else {
329     FAIL() << "Invalid BOM in UTF-16 file";
330   }
331   ASSERT_EQ(strncmp(&buf[2], utf16_text, 16), 0);
332 #else
333   char buf[10];
334   ASSERT_EQ(::read(fd, buf, 10), 10);
335   ASSERT_EQ(strncmp(buf, utf8_text, 10), 0);
336 #endif
337   ::close(fd);
338   ASSERT_NO_ERROR(fs::remove(file_pathname.str()));
339   ASSERT_NO_ERROR(fs::remove(TestDirectory.str()));
340 }
341 
342 TEST_F(ProgramEnvTest, TestExecuteAndWaitStatistics) {
343   using namespace llvm::sys;
344 
345   if (getenv("LLVM_PROGRAM_TEST_STATISTICS"))
346     exit(0);
347 
348   std::string Executable =
349       sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
350   StringRef argv[] = {
351       Executable, "--gtest_filter=ProgramEnvTest.TestExecuteAndWaitStatistics"};
352 
353   // Add LLVM_PROGRAM_TEST_STATISTICS to the environment of the child.
354   addEnvVar("LLVM_PROGRAM_TEST_STATISTICS=1");
355 
356   std::string Error;
357   bool ExecutionFailed;
358   Optional<ProcessStatistics> ProcStat;
359   int RetCode = ExecuteAndWait(Executable, argv, getEnviron(), {}, 0, 0, &Error,
360                                &ExecutionFailed, &ProcStat);
361   ASSERT_EQ(0, RetCode);
362   ASSERT_TRUE(ProcStat);
363   ASSERT_GE(ProcStat->UserTime, std::chrono::microseconds(0));
364   ASSERT_GE(ProcStat->TotalTime, ProcStat->UserTime);
365 }
366 
367 TEST_F(ProgramEnvTest, TestLockFile) {
368   using namespace llvm::sys;
369 
370   if (const char *LockedFile = getenv("LLVM_PROGRAM_TEST_LOCKED_FILE")) {
371     // Child process.
372     int FD2;
373     ASSERT_NO_ERROR(fs::openFileForReadWrite(LockedFile, FD2,
374                                              fs::CD_OpenExisting, fs::OF_None));
375 
376     std::error_code ErrC = fs::tryLockFile(FD2, std::chrono::seconds(5));
377     ASSERT_NO_ERROR(ErrC);
378     ASSERT_NO_ERROR(fs::unlockFile(FD2));
379     close(FD2);
380     exit(0);
381   }
382 
383   // Create file that will be locked.
384   SmallString<64> LockedFile;
385   int FD1;
386   ASSERT_NO_ERROR(
387       fs::createTemporaryFile("TestLockFile", "temp", FD1, LockedFile));
388 
389   std::string Executable =
390       sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
391   StringRef argv[] = {Executable, "--gtest_filter=ProgramEnvTest.TestLockFile"};
392 
393   // Add LLVM_PROGRAM_TEST_LOCKED_FILE to the environment of the child.
394   std::string EnvVar = "LLVM_PROGRAM_TEST_LOCKED_FILE=";
395   EnvVar += LockedFile.str();
396   addEnvVar(EnvVar);
397 
398   // Lock the file.
399   ASSERT_NO_ERROR(fs::tryLockFile(FD1));
400 
401   std::string Error;
402   bool ExecutionFailed;
403   ProcessInfo PI2 = ExecuteNoWait(Executable, argv, getEnviron(), {}, 0, &Error,
404                                   &ExecutionFailed);
405   ASSERT_FALSE(ExecutionFailed) << Error;
406   ASSERT_TRUE(Error.empty());
407   ASSERT_NE(PI2.Pid, ProcessInfo::InvalidPid) << "Invalid process id";
408 
409   // Wait some time to give the child process a chance to start.
410   std::this_thread::sleep_for(std::chrono::milliseconds(100));
411 
412   ASSERT_NO_ERROR(fs::unlockFile(FD1));
413   ProcessInfo WaitResult = llvm::sys::Wait(PI2, 5 /* seconds */, true, &Error);
414   ASSERT_TRUE(Error.empty());
415   ASSERT_EQ(0, WaitResult.ReturnCode);
416   ASSERT_EQ(WaitResult.Pid, PI2.Pid);
417   sys::fs::remove(LockedFile);
418 }
419 
420 } // end anonymous namespace
421