blob: 3926ceb92b3ed5a598e8f0b186e82135557e433b [file] [log] [blame]
Reid Kleckner74679a92013-04-22 19:03:55 +00001//===- 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
Pawel Bylica85ca2942015-11-04 08:25:20 +000010#include "llvm/Support/ConvertUTF.h"
Reid Kleckner74679a92013-04-22 19:03:55 +000011#include "llvm/Support/CommandLine.h"
Rafael Espindolae03dfd92013-06-26 05:01:35 +000012#include "llvm/Support/FileSystem.h"
Reid Kleckner74679a92013-04-22 19:03:55 +000013#include "llvm/Support/Path.h"
14#include "llvm/Support/Program.h"
15#include "gtest/gtest.h"
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000016#include <stdlib.h>
Reid Kleckner206ddd02013-04-24 17:50:30 +000017#if defined(__APPLE__)
Reid Klecknerde0c2602013-04-23 13:15:51 +000018# include <crt_externs.h>
Reid Kleckner206ddd02013-04-24 17:50:30 +000019#elif !defined(_MSC_VER)
Reid Klecknerde0c2602013-04-23 13:15:51 +000020// Forward declare environ in case it's not provided by stdlib.h.
21extern char **environ;
22#endif
Reid Kleckner74679a92013-04-22 19:03:55 +000023
Tareq A. Sirajd88b9832013-10-01 14:28:18 +000024#if defined(LLVM_ON_UNIX)
25#include <unistd.h>
26void sleep_for(unsigned int seconds) {
27 sleep(seconds);
28}
29#elif defined(LLVM_ON_WIN32)
30#include <windows.h>
31void 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
Rafael Espindola9c359662014-09-03 20:02:00 +000038#define ASSERT_NO_ERROR(x) \
39 if (std::error_code ASSERT_NO_ERROR_ec = x) { \
40 SmallString<128> MessageStorage; \
41 raw_svector_ostream Message(MessageStorage); \
42 Message << #x ": did not return errc::success.\n" \
43 << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \
44 << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \
45 GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
46 } else { \
47 }
Reid Kleckner95012aa2013-04-30 04:30:41 +000048// From TestMain.cpp.
49extern const char *TestMainArgv0;
50
Reid Kleckner74679a92013-04-22 19:03:55 +000051namespace {
52
53using namespace llvm;
54using namespace sys;
55
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000056static cl::opt<std::string>
Reid Kleckner74679a92013-04-22 19:03:55 +000057ProgramTestStringArg1("program-test-string-arg1");
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000058static cl::opt<std::string>
Reid Kleckner74679a92013-04-22 19:03:55 +000059ProgramTestStringArg2("program-test-string-arg2");
60
Pawel Bylica85ca2942015-11-04 08:25:20 +000061class ProgramEnvTest : public testing::Test {
62 std::vector<const char *> EnvTable;
63 std::vector<std::string> EnvStorage;
64
65protected:
66 void SetUp() override {
67 auto EnvP = [] {
68#if defined(LLVM_ON_WIN32)
69 _wgetenv(L"TMP"); // Populate _wenviron, initially is null
70 return _wenviron;
71#elif defined(__APPLE__)
72 return *_NSGetEnviron();
Reid Klecknerde0c2602013-04-23 13:15:51 +000073#else
Pawel Bylica85ca2942015-11-04 08:25:20 +000074 return environ;
Reid Klecknerde0c2602013-04-23 13:15:51 +000075#endif
Pawel Bylica85ca2942015-11-04 08:25:20 +000076 }();
77 ASSERT_TRUE(EnvP);
78
79 auto prepareEnvVar = [this](decltype(*EnvP) Var) {
80#if defined(LLVM_ON_WIN32)
81 // On Windows convert UTF16 encoded variable to UTF8
82 auto Len = wcslen(Var);
83 ArrayRef<char> Ref{reinterpret_cast<char const *>(Var),
84 Len * sizeof(*Var)};
85 EnvStorage.emplace_back();
86 auto convStatus = convertUTF16ToUTF8String(Ref, EnvStorage.back());
87 EXPECT_TRUE(convStatus);
88 return EnvStorage.back().c_str();
89#else
Malcolm Parsons17d266b2017-01-13 17:12:16 +000090 (void)this;
Pawel Bylica85ca2942015-11-04 08:25:20 +000091 return Var;
92#endif
93 };
94
95 while (*EnvP != nullptr) {
96 EnvTable.emplace_back(prepareEnvVar(*EnvP));
97 ++EnvP;
98 }
Reid Klecknerde0c2602013-04-23 13:15:51 +000099 }
Pawel Bylica85ca2942015-11-04 08:25:20 +0000100
101 void TearDown() override {
102 EnvTable.clear();
103 EnvStorage.clear();
104 }
105
106 void addEnvVar(const char *Var) {
107 ASSERT_TRUE(EnvTable.empty() || EnvTable.back()) << "Env table sealed";
108 EnvTable.emplace_back(Var);
109 }
110
111 const char **getEnviron() {
112 if (EnvTable.back() != nullptr)
113 EnvTable.emplace_back(nullptr); // Seal table.
114 return &EnvTable[0];
115 }
116};
Reid Klecknerde0c2602013-04-23 13:15:51 +0000117
Paul Robinsonc38deee2014-11-24 18:05:29 +0000118#ifdef LLVM_ON_WIN32
Pawel Bylica85ca2942015-11-04 08:25:20 +0000119TEST_F(ProgramEnvTest, CreateProcessLongPath) {
Paul Robinsonc38deee2014-11-24 18:05:29 +0000120 if (getenv("LLVM_PROGRAM_TEST_LONG_PATH"))
121 exit(0);
122
123 // getMainExecutable returns an absolute path; prepend the long-path prefix.
124 std::string MyAbsExe =
125 sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
126 std::string MyExe;
127 if (!StringRef(MyAbsExe).startswith("\\\\?\\"))
128 MyExe.append("\\\\?\\");
129 MyExe.append(MyAbsExe);
130
131 const char *ArgV[] = {
132 MyExe.c_str(),
Pawel Bylica85ca2942015-11-04 08:25:20 +0000133 "--gtest_filter=ProgramEnvTest.CreateProcessLongPath",
Paul Robinsonc38deee2014-11-24 18:05:29 +0000134 nullptr
135 };
136
137 // Add LLVM_PROGRAM_TEST_LONG_PATH to the environment of the child.
Pawel Bylica85ca2942015-11-04 08:25:20 +0000138 addEnvVar("LLVM_PROGRAM_TEST_LONG_PATH=1");
Paul Robinsonc38deee2014-11-24 18:05:29 +0000139
140 // Redirect stdout to a long path.
141 SmallString<128> TestDirectory;
142 ASSERT_NO_ERROR(
143 fs::createUniqueDirectory("program-redirect-test", TestDirectory));
144 SmallString<256> LongPath(TestDirectory);
145 LongPath.push_back('\\');
146 // MAX_PATH = 260
147 LongPath.append(260 - TestDirectory.size(), 'a');
148 StringRef LongPathRef(LongPath);
149
150 std::string Error;
151 bool ExecutionFailed;
152 const StringRef *Redirects[] = { nullptr, &LongPathRef, nullptr };
Pawel Bylica85ca2942015-11-04 08:25:20 +0000153 int RC = ExecuteAndWait(MyExe, ArgV, getEnviron(), Redirects,
Paul Robinsonc38deee2014-11-24 18:05:29 +0000154 /*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &Error,
155 &ExecutionFailed);
156 EXPECT_FALSE(ExecutionFailed) << Error;
157 EXPECT_EQ(0, RC);
158
159 // Remove the long stdout.
160 ASSERT_NO_ERROR(fs::remove(Twine(LongPath)));
161 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory)));
162}
163#endif
164
Pawel Bylica85ca2942015-11-04 08:25:20 +0000165TEST_F(ProgramEnvTest, CreateProcessTrailingSlash) {
Reid Kleckner74679a92013-04-22 19:03:55 +0000166 if (getenv("LLVM_PROGRAM_TEST_CHILD")) {
167 if (ProgramTestStringArg1 == "has\\\\ trailing\\" &&
168 ProgramTestStringArg2 == "has\\\\ trailing\\") {
169 exit(0); // Success! The arguments were passed and parsed.
170 }
171 exit(1);
172 }
173
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000174 std::string my_exe =
175 sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
Reid Kleckner74679a92013-04-22 19:03:55 +0000176 const char *argv[] = {
177 my_exe.c_str(),
Pawel Bylica85ca2942015-11-04 08:25:20 +0000178 "--gtest_filter=ProgramEnvTest.CreateProcessTrailingSlash",
Reid Kleckner74679a92013-04-22 19:03:55 +0000179 "-program-test-string-arg1", "has\\\\ trailing\\",
180 "-program-test-string-arg2", "has\\\\ trailing\\",
Craig Topper66f09ad2014-06-08 22:29:17 +0000181 nullptr
Reid Kleckner74679a92013-04-22 19:03:55 +0000182 };
Reid Klecknerde0c2602013-04-23 13:15:51 +0000183
184 // Add LLVM_PROGRAM_TEST_CHILD to the environment of the child.
Pawel Bylica85ca2942015-11-04 08:25:20 +0000185 addEnvVar("LLVM_PROGRAM_TEST_CHILD=1");
Reid Klecknerde0c2602013-04-23 13:15:51 +0000186
Reid Kleckner74679a92013-04-22 19:03:55 +0000187 std::string error;
188 bool ExecutionFailed;
189 // Redirect stdout and stdin to NUL, but let stderr through.
190#ifdef LLVM_ON_WIN32
Rafael Espindola7c1023a2013-06-13 20:25:38 +0000191 StringRef nul("NUL");
Reid Kleckner74679a92013-04-22 19:03:55 +0000192#else
Rafael Espindola7c1023a2013-06-13 20:25:38 +0000193 StringRef nul("/dev/null");
Reid Kleckner74679a92013-04-22 19:03:55 +0000194#endif
Craig Topper66f09ad2014-06-08 22:29:17 +0000195 const StringRef *redirects[] = { &nul, &nul, nullptr };
Pawel Bylica85ca2942015-11-04 08:25:20 +0000196 int rc = ExecuteAndWait(my_exe, argv, getEnviron(), redirects,
Rafael Espindola7c1023a2013-06-13 20:25:38 +0000197 /*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &error,
198 &ExecutionFailed);
Reid Kleckner74679a92013-04-22 19:03:55 +0000199 EXPECT_FALSE(ExecutionFailed) << error;
200 EXPECT_EQ(0, rc);
201}
202
Pawel Bylica85ca2942015-11-04 08:25:20 +0000203TEST_F(ProgramEnvTest, TestExecuteNoWait) {
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000204 using namespace llvm::sys;
205
206 if (getenv("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT")) {
207 sleep_for(/*seconds*/ 1);
208 exit(0);
209 }
210
211 std::string Executable =
212 sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
213 const char *argv[] = {
214 Executable.c_str(),
Pawel Bylica85ca2942015-11-04 08:25:20 +0000215 "--gtest_filter=ProgramEnvTest.TestExecuteNoWait",
Craig Topper66f09ad2014-06-08 22:29:17 +0000216 nullptr
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000217 };
218
219 // Add LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT to the environment of the child.
Pawel Bylica85ca2942015-11-04 08:25:20 +0000220 addEnvVar("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT=1");
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000221
222 std::string Error;
223 bool ExecutionFailed;
Pawel Bylica85ca2942015-11-04 08:25:20 +0000224 ProcessInfo PI1 = ExecuteNoWait(Executable, argv, getEnviron(), nullptr, 0,
Craig Topper66f09ad2014-06-08 22:29:17 +0000225 &Error, &ExecutionFailed);
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000226 ASSERT_FALSE(ExecutionFailed) << Error;
Reid Klecknerc2e23112016-02-03 21:41:12 +0000227 ASSERT_NE(PI1.Pid, ProcessInfo::InvalidPid) << "Invalid process id";
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000228
229 unsigned LoopCount = 0;
230
231 // Test that Wait() with WaitUntilTerminates=true works. In this case,
232 // LoopCount should only be incremented once.
233 while (true) {
234 ++LoopCount;
Zachary Turner07670b32016-06-29 21:48:26 +0000235 ProcessInfo WaitResult = llvm::sys::Wait(PI1, 0, true, &Error);
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000236 ASSERT_TRUE(Error.empty());
237 if (WaitResult.Pid == PI1.Pid)
238 break;
239 }
240
241 EXPECT_EQ(LoopCount, 1u) << "LoopCount should be 1";
242
Pawel Bylica85ca2942015-11-04 08:25:20 +0000243 ProcessInfo PI2 = ExecuteNoWait(Executable, argv, getEnviron(), nullptr, 0,
Craig Topper66f09ad2014-06-08 22:29:17 +0000244 &Error, &ExecutionFailed);
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000245 ASSERT_FALSE(ExecutionFailed) << Error;
Reid Klecknerc2e23112016-02-03 21:41:12 +0000246 ASSERT_NE(PI2.Pid, ProcessInfo::InvalidPid) << "Invalid process id";
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000247
248 // Test that Wait() with SecondsToWait=0 performs a non-blocking wait. In this
249 // cse, LoopCount should be greater than 1 (more than one increment occurs).
250 while (true) {
251 ++LoopCount;
Zachary Turner07670b32016-06-29 21:48:26 +0000252 ProcessInfo WaitResult = llvm::sys::Wait(PI2, 0, false, &Error);
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000253 ASSERT_TRUE(Error.empty());
254 if (WaitResult.Pid == PI2.Pid)
255 break;
256 }
257
258 ASSERT_GT(LoopCount, 1u) << "LoopCount should be >1";
259}
260
Pawel Bylica85ca2942015-11-04 08:25:20 +0000261TEST_F(ProgramEnvTest, TestExecuteAndWaitTimeout) {
Peter Collingbourneec1aaca2014-05-31 01:36:02 +0000262 using namespace llvm::sys;
263
264 if (getenv("LLVM_PROGRAM_TEST_TIMEOUT")) {
265 sleep_for(/*seconds*/ 10);
266 exit(0);
267 }
268
269 std::string Executable =
270 sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
271 const char *argv[] = {
272 Executable.c_str(),
Pawel Bylica85ca2942015-11-04 08:25:20 +0000273 "--gtest_filter=ProgramEnvTest.TestExecuteAndWaitTimeout",
Craig Topper66f09ad2014-06-08 22:29:17 +0000274 nullptr
Peter Collingbourneec1aaca2014-05-31 01:36:02 +0000275 };
276
277 // Add LLVM_PROGRAM_TEST_TIMEOUT to the environment of the child.
Pawel Bylica85ca2942015-11-04 08:25:20 +0000278 addEnvVar("LLVM_PROGRAM_TEST_TIMEOUT=1");
Peter Collingbourneec1aaca2014-05-31 01:36:02 +0000279
280 std::string Error;
281 bool ExecutionFailed;
282 int RetCode =
Pawel Bylica85ca2942015-11-04 08:25:20 +0000283 ExecuteAndWait(Executable, argv, getEnviron(), nullptr, /*secondsToWait=*/1, 0,
Peter Collingbourneec1aaca2014-05-31 01:36:02 +0000284 &Error, &ExecutionFailed);
285 ASSERT_EQ(-2, RetCode);
286}
287
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000288TEST(ProgramTest, TestExecuteNegative) {
289 std::string Executable = "i_dont_exist";
Craig Topper66f09ad2014-06-08 22:29:17 +0000290 const char *argv[] = { Executable.c_str(), nullptr };
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000291
292 {
293 std::string Error;
294 bool ExecutionFailed;
Craig Topper66f09ad2014-06-08 22:29:17 +0000295 int RetCode = ExecuteAndWait(Executable, argv, nullptr, nullptr, 0, 0,
296 &Error, &ExecutionFailed);
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000297 ASSERT_TRUE(RetCode < 0) << "On error ExecuteAndWait should return 0 or "
298 "positive value indicating the result code";
299 ASSERT_TRUE(ExecutionFailed);
300 ASSERT_FALSE(Error.empty());
301 }
302
303 {
304 std::string Error;
305 bool ExecutionFailed;
Craig Topper66f09ad2014-06-08 22:29:17 +0000306 ProcessInfo PI = ExecuteNoWait(Executable, argv, nullptr, nullptr, 0,
307 &Error, &ExecutionFailed);
Reid Klecknerc2e23112016-02-03 21:41:12 +0000308 ASSERT_EQ(PI.Pid, ProcessInfo::InvalidPid)
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000309 << "On error ExecuteNoWait should return an invalid ProcessInfo";
310 ASSERT_TRUE(ExecutionFailed);
311 ASSERT_FALSE(Error.empty());
312 }
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000313
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000314}
315
Rafael Espindola9c359662014-09-03 20:02:00 +0000316#ifdef LLVM_ON_WIN32
317const char utf16le_text[] =
318 "\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61\x00";
319const char utf16be_text[] =
320 "\x00\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61";
321#endif
322const char utf8_text[] = "\x6c\x69\x6e\x67\xc3\xbc\x69\xc3\xa7\x61";
323
324TEST(ProgramTest, TestWriteWithSystemEncoding) {
325 SmallString<128> TestDirectory;
326 ASSERT_NO_ERROR(fs::createUniqueDirectory("program-test", TestDirectory));
327 errs() << "Test Directory: " << TestDirectory << '\n';
328 errs().flush();
329 SmallString<128> file_pathname(TestDirectory);
330 path::append(file_pathname, "international-file.txt");
331 // Only on Windows we should encode in UTF16. For other systems, use UTF8
332 ASSERT_NO_ERROR(sys::writeFileWithEncoding(file_pathname.c_str(), utf8_text,
333 sys::WEM_UTF16));
334 int fd = 0;
335 ASSERT_NO_ERROR(fs::openFileForRead(file_pathname.c_str(), fd));
336#if defined(LLVM_ON_WIN32)
337 char buf[18];
338 ASSERT_EQ(::read(fd, buf, 18), 18);
339 if (strncmp(buf, "\xfe\xff", 2) == 0) { // UTF16-BE
340 ASSERT_EQ(strncmp(&buf[2], utf16be_text, 16), 0);
341 } else if (strncmp(buf, "\xff\xfe", 2) == 0) { // UTF16-LE
342 ASSERT_EQ(strncmp(&buf[2], utf16le_text, 16), 0);
343 } else {
344 FAIL() << "Invalid BOM in UTF-16 file";
345 }
346#else
347 char buf[10];
348 ASSERT_EQ(::read(fd, buf, 10), 10);
349 ASSERT_EQ(strncmp(buf, utf8_text, 10), 0);
350#endif
351 ::close(fd);
352 ASSERT_NO_ERROR(fs::remove(file_pathname.str()));
353 ASSERT_NO_ERROR(fs::remove(TestDirectory.str()));
354}
355
Reid Kleckner74679a92013-04-22 19:03:55 +0000356} // end anonymous namespace