Add writeFileWithSystemEncoding to LibLLVMSuppor.
[oota-llvm.git] / unittests / Support / ProgramTest.cpp
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.
20 extern char **environ;
21 #endif
22
23 #if defined(LLVM_ON_UNIX)
24 #include <unistd.h>
25 void sleep_for(unsigned int seconds) {
26   sleep(seconds);
27 }
28 #elif defined(LLVM_ON_WIN32)
29 #include <windows.h>
30 void 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.
48 extern const char *TestMainArgv0;
49
50 namespace {
51
52 using namespace llvm;
53 using namespace sys;
54
55 static cl::opt<std::string>
56 ProgramTestStringArg1("program-test-string-arg1");
57 static cl::opt<std::string>
58 ProgramTestStringArg2("program-test-string-arg2");
59
60 static 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 TEST(ProgramTest, CreateProcessTrailingSlash) {
74   if (getenv("LLVM_PROGRAM_TEST_CHILD")) {
75     if (ProgramTestStringArg1 == "has\\\\ trailing\\" &&
76         ProgramTestStringArg2 == "has\\\\ trailing\\") {
77       exit(0);  // Success!  The arguments were passed and parsed.
78     }
79     exit(1);
80   }
81
82   std::string my_exe =
83       sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
84   const char *argv[] = {
85     my_exe.c_str(),
86     "--gtest_filter=ProgramTest.CreateProcessTrailingSlash",
87     "-program-test-string-arg1", "has\\\\ trailing\\",
88     "-program-test-string-arg2", "has\\\\ trailing\\",
89     nullptr
90   };
91
92   // Add LLVM_PROGRAM_TEST_CHILD to the environment of the child.
93   std::vector<const char *> envp;
94   CopyEnvironment(envp);
95   envp.push_back("LLVM_PROGRAM_TEST_CHILD=1");
96   envp.push_back(nullptr);
97
98   std::string error;
99   bool ExecutionFailed;
100   // Redirect stdout and stdin to NUL, but let stderr through.
101 #ifdef LLVM_ON_WIN32
102   StringRef nul("NUL");
103 #else
104   StringRef nul("/dev/null");
105 #endif
106   const StringRef *redirects[] = { &nul, &nul, nullptr };
107   int rc = ExecuteAndWait(my_exe, argv, &envp[0], redirects,
108                           /*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &error,
109                           &ExecutionFailed);
110   EXPECT_FALSE(ExecutionFailed) << error;
111   EXPECT_EQ(0, rc);
112 }
113
114 TEST(ProgramTest, TestExecuteNoWait) {
115   using namespace llvm::sys;
116
117   if (getenv("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT")) {
118     sleep_for(/*seconds*/ 1);
119     exit(0);
120   }
121
122   std::string Executable =
123       sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
124   const char *argv[] = {
125     Executable.c_str(),
126     "--gtest_filter=ProgramTest.TestExecuteNoWait",
127     nullptr
128   };
129
130   // Add LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT to the environment of the child.
131   std::vector<const char *> envp;
132   CopyEnvironment(envp);
133   envp.push_back("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT=1");
134   envp.push_back(nullptr);
135
136   std::string Error;
137   bool ExecutionFailed;
138   ProcessInfo PI1 = ExecuteNoWait(Executable, argv, &envp[0], nullptr, 0,
139                                   &Error, &ExecutionFailed);
140   ASSERT_FALSE(ExecutionFailed) << Error;
141   ASSERT_NE(PI1.Pid, 0) << "Invalid process id";
142
143   unsigned LoopCount = 0;
144
145   // Test that Wait() with WaitUntilTerminates=true works. In this case,
146   // LoopCount should only be incremented once.
147   while (true) {
148     ++LoopCount;
149     ProcessInfo WaitResult = Wait(PI1, 0, true, &Error);
150     ASSERT_TRUE(Error.empty());
151     if (WaitResult.Pid == PI1.Pid)
152       break;
153   }
154
155   EXPECT_EQ(LoopCount, 1u) << "LoopCount should be 1";
156
157   ProcessInfo PI2 = ExecuteNoWait(Executable, argv, &envp[0], nullptr, 0,
158                                   &Error, &ExecutionFailed);
159   ASSERT_FALSE(ExecutionFailed) << Error;
160   ASSERT_NE(PI2.Pid, 0) << "Invalid process id";
161
162   // Test that Wait() with SecondsToWait=0 performs a non-blocking wait. In this
163   // cse, LoopCount should be greater than 1 (more than one increment occurs).
164   while (true) {
165     ++LoopCount;
166     ProcessInfo WaitResult = Wait(PI2, 0, false, &Error);
167     ASSERT_TRUE(Error.empty());
168     if (WaitResult.Pid == PI2.Pid)
169       break;
170   }
171
172   ASSERT_GT(LoopCount, 1u) << "LoopCount should be >1";
173 }
174
175 TEST(ProgramTest, TestExecuteAndWaitTimeout) {
176   using namespace llvm::sys;
177
178   if (getenv("LLVM_PROGRAM_TEST_TIMEOUT")) {
179     sleep_for(/*seconds*/ 10);
180     exit(0);
181   }
182
183   std::string Executable =
184       sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
185   const char *argv[] = {
186     Executable.c_str(),
187     "--gtest_filter=ProgramTest.TestExecuteAndWaitTimeout",
188     nullptr
189   };
190
191   // Add LLVM_PROGRAM_TEST_TIMEOUT to the environment of the child.
192   std::vector<const char *> envp;
193   CopyEnvironment(envp);
194   envp.push_back("LLVM_PROGRAM_TEST_TIMEOUT=1");
195   envp.push_back(nullptr);
196
197   std::string Error;
198   bool ExecutionFailed;
199   int RetCode =
200       ExecuteAndWait(Executable, argv, &envp[0], nullptr, /*secondsToWait=*/1, 0,
201                      &Error, &ExecutionFailed);
202   ASSERT_EQ(-2, RetCode);
203 }
204
205 TEST(ProgramTest, TestExecuteNegative) {
206   std::string Executable = "i_dont_exist";
207   const char *argv[] = { Executable.c_str(), nullptr };
208
209   {
210     std::string Error;
211     bool ExecutionFailed;
212     int RetCode = ExecuteAndWait(Executable, argv, nullptr, nullptr, 0, 0,
213                                  &Error, &ExecutionFailed);
214     ASSERT_TRUE(RetCode < 0) << "On error ExecuteAndWait should return 0 or "
215                                 "positive value indicating the result code";
216     ASSERT_TRUE(ExecutionFailed);
217     ASSERT_FALSE(Error.empty());
218   }
219
220   {
221     std::string Error;
222     bool ExecutionFailed;
223     ProcessInfo PI = ExecuteNoWait(Executable, argv, nullptr, nullptr, 0,
224                                    &Error, &ExecutionFailed);
225     ASSERT_EQ(PI.Pid, 0)
226         << "On error ExecuteNoWait should return an invalid ProcessInfo";
227     ASSERT_TRUE(ExecutionFailed);
228     ASSERT_FALSE(Error.empty());
229   }
230
231 }
232
233 #ifdef LLVM_ON_WIN32
234 const char utf16le_text[] =
235     "\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61\x00";
236 const char utf16be_text[] =
237     "\x00\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61";
238 #endif
239 const char utf8_text[] = "\x6c\x69\x6e\x67\xc3\xbc\x69\xc3\xa7\x61";
240
241 TEST(ProgramTest, TestWriteWithSystemEncoding) {
242   SmallString<128> TestDirectory;
243   ASSERT_NO_ERROR(fs::createUniqueDirectory("program-test", TestDirectory));
244   errs() << "Test Directory: " << TestDirectory << '\n';
245   errs().flush();
246   SmallString<128> file_pathname(TestDirectory);
247   path::append(file_pathname, "international-file.txt");
248   // Only on Windows we should encode in UTF16. For other systems, use UTF8
249   ASSERT_NO_ERROR(sys::writeFileWithEncoding(file_pathname.c_str(), utf8_text,
250                                              sys::WEM_UTF16));
251   int fd = 0;
252   ASSERT_NO_ERROR(fs::openFileForRead(file_pathname.c_str(), fd));
253 #if defined(LLVM_ON_WIN32)
254   char buf[18];
255   ASSERT_EQ(::read(fd, buf, 18), 18);
256   if (strncmp(buf, "\xfe\xff", 2) == 0) { // UTF16-BE
257     ASSERT_EQ(strncmp(&buf[2], utf16be_text, 16), 0);
258   } else if (strncmp(buf, "\xff\xfe", 2) == 0) { // UTF16-LE
259     ASSERT_EQ(strncmp(&buf[2], utf16le_text, 16), 0);
260   } else {
261     FAIL() << "Invalid BOM in UTF-16 file";
262   }
263 #else
264   char buf[10];
265   ASSERT_EQ(::read(fd, buf, 10), 10);
266   ASSERT_EQ(strncmp(buf, utf8_text, 10), 0);
267 #endif
268   ::close(fd);
269   ASSERT_NO_ERROR(fs::remove(file_pathname.str()));
270   ASSERT_NO_ERROR(fs::remove(TestDirectory.str()));
271 }
272
273 } // end anonymous namespace