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