1 //===- unittest/Support/ProgramTest.cpp -----------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
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;
23 #if defined(LLVM_ON_UNIX)
25 void sleep_for(unsigned int seconds) {
28 #elif defined(LLVM_ON_WIN32)
30 void sleep_for(unsigned int seconds) {
31 Sleep(seconds * 1000);
34 #error sleep_for is not implemented on your platform.
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()); \
48 extern const char *TestMainArgv0;
55 static cl::opt<std::string>
56 ProgramTestStringArg1("program-test-string-arg1");
57 static cl::opt<std::string>
58 ProgramTestStringArg2("program-test-string-arg2");
60 static void CopyEnvironment(std::vector<const char *> &out) {
62 char **envp = *_NSGetEnviron();
64 // environ seems to work for Windows and most other Unices.
65 char **envp = environ;
67 while (*envp != nullptr) {
74 TEST(ProgramTest, CreateProcessLongPath) {
75 if (getenv("LLVM_PROGRAM_TEST_LONG_PATH"))
78 // getMainExecutable returns an absolute path; prepend the long-path prefix.
79 std::string MyAbsExe =
80 sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
82 if (!StringRef(MyAbsExe).startswith("\\\\?\\"))
83 MyExe.append("\\\\?\\");
84 MyExe.append(MyAbsExe);
86 const char *ArgV[] = {
88 "--gtest_filter=ProgramTest.CreateProcessLongPath",
92 // Add LLVM_PROGRAM_TEST_LONG_PATH to the environment of the child.
93 std::vector<const char *> EnvP;
94 CopyEnvironment(EnvP);
95 EnvP.push_back("LLVM_PROGRAM_TEST_LONG_PATH=1");
96 EnvP.push_back(nullptr);
98 // Redirect stdout to a long path.
99 SmallString<128> TestDirectory;
101 fs::createUniqueDirectory("program-redirect-test", TestDirectory));
102 SmallString<256> LongPath(TestDirectory);
103 LongPath.push_back('\\');
105 LongPath.append(260 - TestDirectory.size(), 'a');
106 StringRef LongPathRef(LongPath);
109 bool ExecutionFailed;
110 const StringRef *Redirects[] = { nullptr, &LongPathRef, nullptr };
111 int RC = ExecuteAndWait(MyExe, ArgV, &EnvP[0], Redirects,
112 /*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &Error,
114 EXPECT_FALSE(ExecutionFailed) << Error;
117 // Remove the long stdout.
118 ASSERT_NO_ERROR(fs::remove(Twine(LongPath)));
119 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory)));
123 TEST(ProgramTest, CreateProcessTrailingSlash) {
124 if (getenv("LLVM_PROGRAM_TEST_CHILD")) {
125 if (ProgramTestStringArg1 == "has\\\\ trailing\\" &&
126 ProgramTestStringArg2 == "has\\\\ trailing\\") {
127 exit(0); // Success! The arguments were passed and parsed.
133 sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
134 const char *argv[] = {
136 "--gtest_filter=ProgramTest.CreateProcessTrailingSlash",
137 "-program-test-string-arg1", "has\\\\ trailing\\",
138 "-program-test-string-arg2", "has\\\\ trailing\\",
142 // Add LLVM_PROGRAM_TEST_CHILD to the environment of the child.
143 std::vector<const char *> envp;
144 CopyEnvironment(envp);
145 envp.push_back("LLVM_PROGRAM_TEST_CHILD=1");
146 envp.push_back(nullptr);
149 bool ExecutionFailed;
150 // Redirect stdout and stdin to NUL, but let stderr through.
152 StringRef nul("NUL");
154 StringRef nul("/dev/null");
156 const StringRef *redirects[] = { &nul, &nul, nullptr };
157 int rc = ExecuteAndWait(my_exe, argv, &envp[0], redirects,
158 /*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &error,
160 EXPECT_FALSE(ExecutionFailed) << error;
164 TEST(ProgramTest, TestExecuteNoWait) {
165 using namespace llvm::sys;
167 if (getenv("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT")) {
168 sleep_for(/*seconds*/ 1);
172 std::string Executable =
173 sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
174 const char *argv[] = {
176 "--gtest_filter=ProgramTest.TestExecuteNoWait",
180 // Add LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT to the environment of the child.
181 std::vector<const char *> envp;
182 CopyEnvironment(envp);
183 envp.push_back("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT=1");
184 envp.push_back(nullptr);
187 bool ExecutionFailed;
188 ProcessInfo PI1 = ExecuteNoWait(Executable, argv, &envp[0], nullptr, 0,
189 &Error, &ExecutionFailed);
190 ASSERT_FALSE(ExecutionFailed) << Error;
191 ASSERT_NE(PI1.Pid, 0) << "Invalid process id";
193 unsigned LoopCount = 0;
195 // Test that Wait() with WaitUntilTerminates=true works. In this case,
196 // LoopCount should only be incremented once.
199 ProcessInfo WaitResult = Wait(PI1, 0, true, &Error);
200 ASSERT_TRUE(Error.empty());
201 if (WaitResult.Pid == PI1.Pid)
205 EXPECT_EQ(LoopCount, 1u) << "LoopCount should be 1";
207 ProcessInfo PI2 = ExecuteNoWait(Executable, argv, &envp[0], nullptr, 0,
208 &Error, &ExecutionFailed);
209 ASSERT_FALSE(ExecutionFailed) << Error;
210 ASSERT_NE(PI2.Pid, 0) << "Invalid process id";
212 // Test that Wait() with SecondsToWait=0 performs a non-blocking wait. In this
213 // cse, LoopCount should be greater than 1 (more than one increment occurs).
216 ProcessInfo WaitResult = Wait(PI2, 0, false, &Error);
217 ASSERT_TRUE(Error.empty());
218 if (WaitResult.Pid == PI2.Pid)
222 ASSERT_GT(LoopCount, 1u) << "LoopCount should be >1";
225 TEST(ProgramTest, TestExecuteAndWaitTimeout) {
226 using namespace llvm::sys;
228 if (getenv("LLVM_PROGRAM_TEST_TIMEOUT")) {
229 sleep_for(/*seconds*/ 10);
233 std::string Executable =
234 sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
235 const char *argv[] = {
237 "--gtest_filter=ProgramTest.TestExecuteAndWaitTimeout",
241 // Add LLVM_PROGRAM_TEST_TIMEOUT to the environment of the child.
242 std::vector<const char *> envp;
243 CopyEnvironment(envp);
244 envp.push_back("LLVM_PROGRAM_TEST_TIMEOUT=1");
245 envp.push_back(nullptr);
248 bool ExecutionFailed;
250 ExecuteAndWait(Executable, argv, &envp[0], nullptr, /*secondsToWait=*/1, 0,
251 &Error, &ExecutionFailed);
252 ASSERT_EQ(-2, RetCode);
255 TEST(ProgramTest, TestExecuteNegative) {
256 std::string Executable = "i_dont_exist";
257 const char *argv[] = { Executable.c_str(), nullptr };
261 bool ExecutionFailed;
262 int RetCode = ExecuteAndWait(Executable, argv, nullptr, nullptr, 0, 0,
263 &Error, &ExecutionFailed);
264 ASSERT_TRUE(RetCode < 0) << "On error ExecuteAndWait should return 0 or "
265 "positive value indicating the result code";
266 ASSERT_TRUE(ExecutionFailed);
267 ASSERT_FALSE(Error.empty());
272 bool ExecutionFailed;
273 ProcessInfo PI = ExecuteNoWait(Executable, argv, nullptr, nullptr, 0,
274 &Error, &ExecutionFailed);
276 << "On error ExecuteNoWait should return an invalid ProcessInfo";
277 ASSERT_TRUE(ExecutionFailed);
278 ASSERT_FALSE(Error.empty());
284 const char utf16le_text[] =
285 "\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61\x00";
286 const char utf16be_text[] =
287 "\x00\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61";
289 const char utf8_text[] = "\x6c\x69\x6e\x67\xc3\xbc\x69\xc3\xa7\x61";
291 TEST(ProgramTest, TestWriteWithSystemEncoding) {
292 SmallString<128> TestDirectory;
293 ASSERT_NO_ERROR(fs::createUniqueDirectory("program-test", TestDirectory));
294 errs() << "Test Directory: " << TestDirectory << '\n';
296 SmallString<128> file_pathname(TestDirectory);
297 path::append(file_pathname, "international-file.txt");
298 // Only on Windows we should encode in UTF16. For other systems, use UTF8
299 ASSERT_NO_ERROR(sys::writeFileWithEncoding(file_pathname.c_str(), utf8_text,
302 ASSERT_NO_ERROR(fs::openFileForRead(file_pathname.c_str(), fd));
303 #if defined(LLVM_ON_WIN32)
305 ASSERT_EQ(::read(fd, buf, 18), 18);
306 if (strncmp(buf, "\xfe\xff", 2) == 0) { // UTF16-BE
307 ASSERT_EQ(strncmp(&buf[2], utf16be_text, 16), 0);
308 } else if (strncmp(buf, "\xff\xfe", 2) == 0) { // UTF16-LE
309 ASSERT_EQ(strncmp(&buf[2], utf16le_text, 16), 0);
311 FAIL() << "Invalid BOM in UTF-16 file";
315 ASSERT_EQ(::read(fd, buf, 10), 10);
316 ASSERT_EQ(strncmp(buf, utf8_text, 10), 0);
319 ASSERT_NO_ERROR(fs::remove(file_pathname.str()));
320 ASSERT_NO_ERROR(fs::remove(TestDirectory.str()));
323 } // end anonymous namespace