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