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/Program.h"
11 #include "llvm/Config/llvm-config.h"
12 #include "llvm/Support/CommandLine.h"
13 #include "llvm/Support/ConvertUTF.h"
14 #include "llvm/Support/FileSystem.h"
15 #include "llvm/Support/Path.h"
16 #include "gtest/gtest.h"
18 #if defined(__APPLE__)
19 # include <crt_externs.h>
20 #elif !defined(_MSC_VER)
21 // Forward declare environ in case it's not provided by stdlib.h.
22 extern char **environ;
25 #if defined(LLVM_ON_UNIX)
27 void sleep_for(unsigned int seconds) {
32 void sleep_for(unsigned int seconds) {
33 Sleep(seconds * 1000);
36 #error sleep_for is not implemented on your platform.
39 #define ASSERT_NO_ERROR(x) \
40 if (std::error_code ASSERT_NO_ERROR_ec = x) { \
41 SmallString<128> MessageStorage; \
42 raw_svector_ostream Message(MessageStorage); \
43 Message << #x ": did not return errc::success.\n" \
44 << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \
45 << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \
46 GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
50 extern const char *TestMainArgv0;
57 static cl::opt<std::string>
58 ProgramTestStringArg1("program-test-string-arg1");
59 static cl::opt<std::string>
60 ProgramTestStringArg2("program-test-string-arg2");
62 class ProgramEnvTest : public testing::Test {
63 std::vector<StringRef> EnvTable;
64 std::vector<std::string> EnvStorage;
67 void SetUp() override {
70 _wgetenv(L"TMP"); // Populate _wenviron, initially is null
72 #elif defined(__APPLE__)
73 return *_NSGetEnviron();
80 auto prepareEnvVar = [this](decltype(*EnvP) Var) -> StringRef {
82 // On Windows convert UTF16 encoded variable to UTF8
83 auto Len = wcslen(Var);
84 ArrayRef<char> Ref{reinterpret_cast<char const *>(Var),
86 EnvStorage.emplace_back();
87 auto convStatus = convertUTF16ToUTF8String(Ref, EnvStorage.back());
88 EXPECT_TRUE(convStatus);
89 return EnvStorage.back();
92 return StringRef(Var);
96 while (*EnvP != nullptr) {
97 EnvTable.emplace_back(prepareEnvVar(*EnvP));
102 void TearDown() override {
107 void addEnvVar(StringRef Var) { EnvTable.emplace_back(Var); }
109 ArrayRef<StringRef> getEnviron() const { return EnvTable; }
113 TEST_F(ProgramEnvTest, CreateProcessLongPath) {
114 if (getenv("LLVM_PROGRAM_TEST_LONG_PATH"))
117 // getMainExecutable returns an absolute path; prepend the long-path prefix.
118 std::string MyAbsExe =
119 sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
121 if (!StringRef(MyAbsExe).startswith("\\\\?\\"))
122 MyExe.append("\\\\?\\");
123 MyExe.append(MyAbsExe);
125 StringRef ArgV[] = {MyExe,
126 "--gtest_filter=ProgramEnvTest.CreateProcessLongPath"};
128 // Add LLVM_PROGRAM_TEST_LONG_PATH to the environment of the child.
129 addEnvVar("LLVM_PROGRAM_TEST_LONG_PATH=1");
131 // Redirect stdout to a long path.
132 SmallString<128> TestDirectory;
134 fs::createUniqueDirectory("program-redirect-test", TestDirectory));
135 SmallString<256> LongPath(TestDirectory);
136 LongPath.push_back('\\');
138 LongPath.append(260 - TestDirectory.size(), 'a');
141 bool ExecutionFailed;
142 Optional<StringRef> Redirects[] = {None, LongPath.str(), None};
143 int RC = ExecuteAndWait(MyExe, ArgV, getEnviron(), Redirects,
144 /*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &Error,
146 EXPECT_FALSE(ExecutionFailed) << Error;
149 // Remove the long stdout.
150 ASSERT_NO_ERROR(fs::remove(Twine(LongPath)));
151 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory)));
155 TEST_F(ProgramEnvTest, CreateProcessTrailingSlash) {
156 if (getenv("LLVM_PROGRAM_TEST_CHILD")) {
157 if (ProgramTestStringArg1 == "has\\\\ trailing\\" &&
158 ProgramTestStringArg2 == "has\\\\ trailing\\") {
159 exit(0); // Success! The arguments were passed and parsed.
165 sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
168 "--gtest_filter=ProgramEnvTest.CreateProcessTrailingSlash",
169 "-program-test-string-arg1",
170 "has\\\\ trailing\\",
171 "-program-test-string-arg2",
172 "has\\\\ trailing\\"};
174 // Add LLVM_PROGRAM_TEST_CHILD to the environment of the child.
175 addEnvVar("LLVM_PROGRAM_TEST_CHILD=1");
178 bool ExecutionFailed;
179 // Redirect stdout and stdin to NUL, but let stderr through.
181 StringRef nul("NUL");
183 StringRef nul("/dev/null");
185 Optional<StringRef> redirects[] = { nul, nul, None };
186 int rc = ExecuteAndWait(my_exe, argv, getEnviron(), redirects,
187 /*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &error,
189 EXPECT_FALSE(ExecutionFailed) << error;
193 TEST_F(ProgramEnvTest, TestExecuteNoWait) {
194 using namespace llvm::sys;
196 if (getenv("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT")) {
197 sleep_for(/*seconds*/ 1);
201 std::string Executable =
202 sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
203 StringRef argv[] = {Executable,
204 "--gtest_filter=ProgramEnvTest.TestExecuteNoWait"};
206 // Add LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT to the environment of the child.
207 addEnvVar("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT=1");
210 bool ExecutionFailed;
211 ProcessInfo PI1 = ExecuteNoWait(Executable, argv, getEnviron(), {}, 0, &Error,
213 ASSERT_FALSE(ExecutionFailed) << Error;
214 ASSERT_NE(PI1.Pid, ProcessInfo::InvalidPid) << "Invalid process id";
216 unsigned LoopCount = 0;
218 // Test that Wait() with WaitUntilTerminates=true works. In this case,
219 // LoopCount should only be incremented once.
222 ProcessInfo WaitResult = llvm::sys::Wait(PI1, 0, true, &Error);
223 ASSERT_TRUE(Error.empty());
224 if (WaitResult.Pid == PI1.Pid)
228 EXPECT_EQ(LoopCount, 1u) << "LoopCount should be 1";
230 ProcessInfo PI2 = ExecuteNoWait(Executable, argv, getEnviron(), {}, 0, &Error,
232 ASSERT_FALSE(ExecutionFailed) << Error;
233 ASSERT_NE(PI2.Pid, ProcessInfo::InvalidPid) << "Invalid process id";
235 // Test that Wait() with SecondsToWait=0 performs a non-blocking wait. In this
236 // cse, LoopCount should be greater than 1 (more than one increment occurs).
239 ProcessInfo WaitResult = llvm::sys::Wait(PI2, 0, false, &Error);
240 ASSERT_TRUE(Error.empty());
241 if (WaitResult.Pid == PI2.Pid)
245 ASSERT_GT(LoopCount, 1u) << "LoopCount should be >1";
248 TEST_F(ProgramEnvTest, TestExecuteAndWaitTimeout) {
249 using namespace llvm::sys;
251 if (getenv("LLVM_PROGRAM_TEST_TIMEOUT")) {
252 sleep_for(/*seconds*/ 10);
256 std::string Executable =
257 sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
259 Executable, "--gtest_filter=ProgramEnvTest.TestExecuteAndWaitTimeout"};
261 // Add LLVM_PROGRAM_TEST_TIMEOUT to the environment of the child.
262 addEnvVar("LLVM_PROGRAM_TEST_TIMEOUT=1");
265 bool ExecutionFailed;
267 ExecuteAndWait(Executable, argv, getEnviron(), {}, /*secondsToWait=*/1, 0,
268 &Error, &ExecutionFailed);
269 ASSERT_EQ(-2, RetCode);
272 TEST(ProgramTest, TestExecuteNegative) {
273 std::string Executable = "i_dont_exist";
274 StringRef argv[] = {Executable};
278 bool ExecutionFailed;
279 int RetCode = ExecuteAndWait(Executable, argv, llvm::None, {}, 0, 0, &Error,
281 ASSERT_TRUE(RetCode < 0) << "On error ExecuteAndWait should return 0 or "
282 "positive value indicating the result code";
283 ASSERT_TRUE(ExecutionFailed);
284 ASSERT_FALSE(Error.empty());
289 bool ExecutionFailed;
290 ProcessInfo PI = ExecuteNoWait(Executable, argv, llvm::None, {}, 0, &Error,
292 ASSERT_EQ(PI.Pid, ProcessInfo::InvalidPid)
293 << "On error ExecuteNoWait should return an invalid ProcessInfo";
294 ASSERT_TRUE(ExecutionFailed);
295 ASSERT_FALSE(Error.empty());
301 const char utf16le_text[] =
302 "\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61\x00";
303 const char utf16be_text[] =
304 "\x00\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61";
306 const char utf8_text[] = "\x6c\x69\x6e\x67\xc3\xbc\x69\xc3\xa7\x61";
308 TEST(ProgramTest, TestWriteWithSystemEncoding) {
309 SmallString<128> TestDirectory;
310 ASSERT_NO_ERROR(fs::createUniqueDirectory("program-test", TestDirectory));
311 errs() << "Test Directory: " << TestDirectory << '\n';
313 SmallString<128> file_pathname(TestDirectory);
314 path::append(file_pathname, "international-file.txt");
315 // Only on Windows we should encode in UTF16. For other systems, use UTF8
316 ASSERT_NO_ERROR(sys::writeFileWithEncoding(file_pathname.c_str(), utf8_text,
319 ASSERT_NO_ERROR(fs::openFileForRead(file_pathname.c_str(), fd));
322 ASSERT_EQ(::read(fd, buf, 18), 18);
323 if (strncmp(buf, "\xfe\xff", 2) == 0) { // UTF16-BE
324 ASSERT_EQ(strncmp(&buf[2], utf16be_text, 16), 0);
325 } else if (strncmp(buf, "\xff\xfe", 2) == 0) { // UTF16-LE
326 ASSERT_EQ(strncmp(&buf[2], utf16le_text, 16), 0);
328 FAIL() << "Invalid BOM in UTF-16 file";
332 ASSERT_EQ(::read(fd, buf, 10), 10);
333 ASSERT_EQ(strncmp(buf, utf8_text, 10), 0);
336 ASSERT_NO_ERROR(fs::remove(file_pathname.str()));
337 ASSERT_NO_ERROR(fs::remove(TestDirectory.str()));
340 } // end anonymous namespace