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/Program.h" 11 #include "llvm/Support/CommandLine.h" 12 #include "llvm/Support/ConvertUTF.h" 13 #include "llvm/Support/FileSystem.h" 14 #include "llvm/Support/Path.h" 15 #include "gtest/gtest.h" 16 #include <stdlib.h> 17 #if defined(__APPLE__) 18 # include <crt_externs.h> 19 #elif !defined(_MSC_VER) 20 // Forward declare environ in case it's not provided by stdlib.h. 21 extern char **environ; 22 #endif 23 24 #if defined(LLVM_ON_UNIX) 25 #include <unistd.h> 26 void sleep_for(unsigned int seconds) { 27 sleep(seconds); 28 } 29 #elif defined(LLVM_ON_WIN32) 30 #include <windows.h> 31 void 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 38 #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 } 48 // From TestMain.cpp. 49 extern const char *TestMainArgv0; 50 51 namespace { 52 53 using namespace llvm; 54 using namespace sys; 55 56 static cl::opt<std::string> 57 ProgramTestStringArg1("program-test-string-arg1"); 58 static cl::opt<std::string> 59 ProgramTestStringArg2("program-test-string-arg2"); 60 61 class ProgramEnvTest : public testing::Test { 62 std::vector<const char *> EnvTable; 63 std::vector<std::string> EnvStorage; 64 65 protected: 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(); 73 #else 74 return environ; 75 #endif 76 }(); 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 90 (void)this; 91 return Var; 92 #endif 93 }; 94 95 while (*EnvP != nullptr) { 96 EnvTable.emplace_back(prepareEnvVar(*EnvP)); 97 ++EnvP; 98 } 99 } 100 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 }; 117 118 #ifdef LLVM_ON_WIN32 119 TEST_F(ProgramEnvTest, CreateProcessLongPath) { 120 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(), 133 "--gtest_filter=ProgramEnvTest.CreateProcessLongPath", 134 nullptr 135 }; 136 137 // Add LLVM_PROGRAM_TEST_LONG_PATH to the environment of the child. 138 addEnvVar("LLVM_PROGRAM_TEST_LONG_PATH=1"); 139 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 }; 153 int RC = ExecuteAndWait(MyExe, ArgV, getEnviron(), Redirects, 154 /*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 165 TEST_F(ProgramEnvTest, CreateProcessTrailingSlash) { 166 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 174 std::string my_exe = 175 sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1); 176 const char *argv[] = { 177 my_exe.c_str(), 178 "--gtest_filter=ProgramEnvTest.CreateProcessTrailingSlash", 179 "-program-test-string-arg1", "has\\\\ trailing\\", 180 "-program-test-string-arg2", "has\\\\ trailing\\", 181 nullptr 182 }; 183 184 // Add LLVM_PROGRAM_TEST_CHILD to the environment of the child. 185 addEnvVar("LLVM_PROGRAM_TEST_CHILD=1"); 186 187 std::string error; 188 bool ExecutionFailed; 189 // Redirect stdout and stdin to NUL, but let stderr through. 190 #ifdef LLVM_ON_WIN32 191 StringRef nul("NUL"); 192 #else 193 StringRef nul("/dev/null"); 194 #endif 195 const StringRef *redirects[] = { &nul, &nul, nullptr }; 196 int rc = ExecuteAndWait(my_exe, argv, getEnviron(), redirects, 197 /*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &error, 198 &ExecutionFailed); 199 EXPECT_FALSE(ExecutionFailed) << error; 200 EXPECT_EQ(0, rc); 201 } 202 203 TEST_F(ProgramEnvTest, TestExecuteNoWait) { 204 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(), 215 "--gtest_filter=ProgramEnvTest.TestExecuteNoWait", 216 nullptr 217 }; 218 219 // Add LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT to the environment of the child. 220 addEnvVar("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT=1"); 221 222 std::string Error; 223 bool ExecutionFailed; 224 ProcessInfo PI1 = ExecuteNoWait(Executable, argv, getEnviron(), nullptr, 0, 225 &Error, &ExecutionFailed); 226 ASSERT_FALSE(ExecutionFailed) << Error; 227 ASSERT_NE(PI1.Pid, ProcessInfo::InvalidPid) << "Invalid process id"; 228 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; 235 ProcessInfo WaitResult = llvm::sys::Wait(PI1, 0, true, &Error); 236 ASSERT_TRUE(Error.empty()); 237 if (WaitResult.Pid == PI1.Pid) 238 break; 239 } 240 241 EXPECT_EQ(LoopCount, 1u) << "LoopCount should be 1"; 242 243 ProcessInfo PI2 = ExecuteNoWait(Executable, argv, getEnviron(), nullptr, 0, 244 &Error, &ExecutionFailed); 245 ASSERT_FALSE(ExecutionFailed) << Error; 246 ASSERT_NE(PI2.Pid, ProcessInfo::InvalidPid) << "Invalid process id"; 247 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; 252 ProcessInfo WaitResult = llvm::sys::Wait(PI2, 0, false, &Error); 253 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 261 TEST_F(ProgramEnvTest, TestExecuteAndWaitTimeout) { 262 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(), 273 "--gtest_filter=ProgramEnvTest.TestExecuteAndWaitTimeout", 274 nullptr 275 }; 276 277 // Add LLVM_PROGRAM_TEST_TIMEOUT to the environment of the child. 278 addEnvVar("LLVM_PROGRAM_TEST_TIMEOUT=1"); 279 280 std::string Error; 281 bool ExecutionFailed; 282 int RetCode = 283 ExecuteAndWait(Executable, argv, getEnviron(), nullptr, /*secondsToWait=*/1, 0, 284 &Error, &ExecutionFailed); 285 ASSERT_EQ(-2, RetCode); 286 } 287 288 TEST(ProgramTest, TestExecuteNegative) { 289 std::string Executable = "i_dont_exist"; 290 const char *argv[] = { Executable.c_str(), nullptr }; 291 292 { 293 std::string Error; 294 bool ExecutionFailed; 295 int RetCode = ExecuteAndWait(Executable, argv, nullptr, nullptr, 0, 0, 296 &Error, &ExecutionFailed); 297 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; 306 ProcessInfo PI = ExecuteNoWait(Executable, argv, nullptr, nullptr, 0, 307 &Error, &ExecutionFailed); 308 ASSERT_EQ(PI.Pid, ProcessInfo::InvalidPid) 309 << "On error ExecuteNoWait should return an invalid ProcessInfo"; 310 ASSERT_TRUE(ExecutionFailed); 311 ASSERT_FALSE(Error.empty()); 312 } 313 314 } 315 316 #ifdef LLVM_ON_WIN32 317 const char utf16le_text[] = 318 "\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61\x00"; 319 const char utf16be_text[] = 320 "\x00\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61"; 321 #endif 322 const char utf8_text[] = "\x6c\x69\x6e\x67\xc3\xbc\x69\xc3\xa7\x61"; 323 324 TEST(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 356 } // end anonymous namespace 357