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