ProgramTest.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. #include "llvm/Support/Program.h"
  10. #include "llvm/Config/llvm-config.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. #if defined(LLVM_ON_UNIX)
  24. #include <unistd.h>
  25. void sleep_for(unsigned int seconds) {
  26. sleep(seconds);
  27. }
  28. #elif defined(_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. #define ASSERT_NO_ERROR(x) \
  37. if (std::error_code ASSERT_NO_ERROR_ec = x) { \
  38. SmallString<128> MessageStorage; \
  39. raw_svector_ostream Message(MessageStorage); \
  40. Message << #x ": did not return errc::success.\n" \
  41. << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \
  42. << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \
  43. GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
  44. } else { \
  45. }
  46. // From TestMain.cpp.
  47. extern const char *TestMainArgv0;
  48. namespace {
  49. using namespace llvm;
  50. using namespace sys;
  51. static cl::opt<std::string>
  52. ProgramTestStringArg1("program-test-string-arg1");
  53. static cl::opt<std::string>
  54. ProgramTestStringArg2("program-test-string-arg2");
  55. class ProgramEnvTest : public testing::Test {
  56. std::vector<StringRef> EnvTable;
  57. std::vector<std::string> EnvStorage;
  58. protected:
  59. void SetUp() override {
  60. auto EnvP = [] {
  61. #if defined(_WIN32)
  62. _wgetenv(L"TMP"); // Populate _wenviron, initially is null
  63. return _wenviron;
  64. #elif defined(__APPLE__)
  65. return *_NSGetEnviron();
  66. #else
  67. return environ;
  68. #endif
  69. }();
  70. ASSERT_TRUE(EnvP);
  71. auto prepareEnvVar = [this](decltype(*EnvP) Var) -> StringRef {
  72. #if defined(_WIN32)
  73. // On Windows convert UTF16 encoded variable to UTF8
  74. auto Len = wcslen(Var);
  75. ArrayRef<char> Ref{reinterpret_cast<char const *>(Var),
  76. Len * sizeof(*Var)};
  77. EnvStorage.emplace_back();
  78. auto convStatus = convertUTF16ToUTF8String(Ref, EnvStorage.back());
  79. EXPECT_TRUE(convStatus);
  80. return EnvStorage.back();
  81. #else
  82. (void)this;
  83. return StringRef(Var);
  84. #endif
  85. };
  86. while (*EnvP != nullptr) {
  87. EnvTable.emplace_back(prepareEnvVar(*EnvP));
  88. ++EnvP;
  89. }
  90. }
  91. void TearDown() override {
  92. EnvTable.clear();
  93. EnvStorage.clear();
  94. }
  95. void addEnvVar(StringRef Var) { EnvTable.emplace_back(Var); }
  96. ArrayRef<StringRef> getEnviron() const { return EnvTable; }
  97. };
  98. #ifdef _WIN32
  99. TEST_F(ProgramEnvTest, CreateProcessLongPath) {
  100. if (getenv("LLVM_PROGRAM_TEST_LONG_PATH"))
  101. exit(0);
  102. // getMainExecutable returns an absolute path; prepend the long-path prefix.
  103. std::string MyAbsExe =
  104. sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
  105. std::string MyExe;
  106. if (!StringRef(MyAbsExe).startswith("\\\\?\\"))
  107. MyExe.append("\\\\?\\");
  108. MyExe.append(MyAbsExe);
  109. StringRef ArgV[] = {MyExe,
  110. "--gtest_filter=ProgramEnvTest.CreateProcessLongPath"};
  111. // Add LLVM_PROGRAM_TEST_LONG_PATH to the environment of the child.
  112. addEnvVar("LLVM_PROGRAM_TEST_LONG_PATH=1");
  113. // Redirect stdout to a long path.
  114. SmallString<128> TestDirectory;
  115. ASSERT_NO_ERROR(
  116. fs::createUniqueDirectory("program-redirect-test", TestDirectory));
  117. SmallString<256> LongPath(TestDirectory);
  118. LongPath.push_back('\\');
  119. // MAX_PATH = 260
  120. LongPath.append(260 - TestDirectory.size(), 'a');
  121. std::string Error;
  122. bool ExecutionFailed;
  123. Optional<StringRef> Redirects[] = {None, LongPath.str(), None};
  124. int RC = ExecuteAndWait(MyExe, ArgV, getEnviron(), Redirects,
  125. /*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &Error,
  126. &ExecutionFailed);
  127. EXPECT_FALSE(ExecutionFailed) << Error;
  128. EXPECT_EQ(0, RC);
  129. // Remove the long stdout.
  130. ASSERT_NO_ERROR(fs::remove(Twine(LongPath)));
  131. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory)));
  132. }
  133. #endif
  134. TEST_F(ProgramEnvTest, CreateProcessTrailingSlash) {
  135. if (getenv("LLVM_PROGRAM_TEST_CHILD")) {
  136. if (ProgramTestStringArg1 == "has\\\\ trailing\\" &&
  137. ProgramTestStringArg2 == "has\\\\ trailing\\") {
  138. exit(0); // Success! The arguments were passed and parsed.
  139. }
  140. exit(1);
  141. }
  142. std::string my_exe =
  143. sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
  144. StringRef argv[] = {
  145. my_exe,
  146. "--gtest_filter=ProgramEnvTest.CreateProcessTrailingSlash",
  147. "-program-test-string-arg1",
  148. "has\\\\ trailing\\",
  149. "-program-test-string-arg2",
  150. "has\\\\ trailing\\"};
  151. // Add LLVM_PROGRAM_TEST_CHILD to the environment of the child.
  152. addEnvVar("LLVM_PROGRAM_TEST_CHILD=1");
  153. std::string error;
  154. bool ExecutionFailed;
  155. // Redirect stdout and stdin to NUL, but let stderr through.
  156. #ifdef _WIN32
  157. StringRef nul("NUL");
  158. #else
  159. StringRef nul("/dev/null");
  160. #endif
  161. Optional<StringRef> redirects[] = { nul, nul, None };
  162. int rc = ExecuteAndWait(my_exe, argv, getEnviron(), redirects,
  163. /*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &error,
  164. &ExecutionFailed);
  165. EXPECT_FALSE(ExecutionFailed) << error;
  166. EXPECT_EQ(0, rc);
  167. }
  168. TEST_F(ProgramEnvTest, TestExecuteNoWait) {
  169. using namespace llvm::sys;
  170. if (getenv("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT")) {
  171. sleep_for(/*seconds*/ 1);
  172. exit(0);
  173. }
  174. std::string Executable =
  175. sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
  176. StringRef argv[] = {Executable,
  177. "--gtest_filter=ProgramEnvTest.TestExecuteNoWait"};
  178. // Add LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT to the environment of the child.
  179. addEnvVar("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT=1");
  180. std::string Error;
  181. bool ExecutionFailed;
  182. ProcessInfo PI1 = ExecuteNoWait(Executable, argv, getEnviron(), {}, 0, &Error,
  183. &ExecutionFailed);
  184. ASSERT_FALSE(ExecutionFailed) << Error;
  185. ASSERT_NE(PI1.Pid, ProcessInfo::InvalidPid) << "Invalid process id";
  186. unsigned LoopCount = 0;
  187. // Test that Wait() with WaitUntilTerminates=true works. In this case,
  188. // LoopCount should only be incremented once.
  189. while (true) {
  190. ++LoopCount;
  191. ProcessInfo WaitResult = llvm::sys::Wait(PI1, 0, true, &Error);
  192. ASSERT_TRUE(Error.empty());
  193. if (WaitResult.Pid == PI1.Pid)
  194. break;
  195. }
  196. EXPECT_EQ(LoopCount, 1u) << "LoopCount should be 1";
  197. ProcessInfo PI2 = ExecuteNoWait(Executable, argv, getEnviron(), {}, 0, &Error,
  198. &ExecutionFailed);
  199. ASSERT_FALSE(ExecutionFailed) << Error;
  200. ASSERT_NE(PI2.Pid, ProcessInfo::InvalidPid) << "Invalid process id";
  201. // Test that Wait() with SecondsToWait=0 performs a non-blocking wait. In this
  202. // cse, LoopCount should be greater than 1 (more than one increment occurs).
  203. while (true) {
  204. ++LoopCount;
  205. ProcessInfo WaitResult = llvm::sys::Wait(PI2, 0, false, &Error);
  206. ASSERT_TRUE(Error.empty());
  207. if (WaitResult.Pid == PI2.Pid)
  208. break;
  209. }
  210. ASSERT_GT(LoopCount, 1u) << "LoopCount should be >1";
  211. }
  212. TEST_F(ProgramEnvTest, TestExecuteAndWaitTimeout) {
  213. using namespace llvm::sys;
  214. if (getenv("LLVM_PROGRAM_TEST_TIMEOUT")) {
  215. sleep_for(/*seconds*/ 10);
  216. exit(0);
  217. }
  218. std::string Executable =
  219. sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
  220. StringRef argv[] = {
  221. Executable, "--gtest_filter=ProgramEnvTest.TestExecuteAndWaitTimeout"};
  222. // Add LLVM_PROGRAM_TEST_TIMEOUT to the environment of the child.
  223. addEnvVar("LLVM_PROGRAM_TEST_TIMEOUT=1");
  224. std::string Error;
  225. bool ExecutionFailed;
  226. int RetCode =
  227. ExecuteAndWait(Executable, argv, getEnviron(), {}, /*secondsToWait=*/1, 0,
  228. &Error, &ExecutionFailed);
  229. ASSERT_EQ(-2, RetCode);
  230. }
  231. TEST(ProgramTest, TestExecuteNegative) {
  232. std::string Executable = "i_dont_exist";
  233. StringRef argv[] = {Executable};
  234. {
  235. std::string Error;
  236. bool ExecutionFailed;
  237. int RetCode = ExecuteAndWait(Executable, argv, llvm::None, {}, 0, 0, &Error,
  238. &ExecutionFailed);
  239. ASSERT_TRUE(RetCode < 0) << "On error ExecuteAndWait should return 0 or "
  240. "positive value indicating the result code";
  241. ASSERT_TRUE(ExecutionFailed);
  242. ASSERT_FALSE(Error.empty());
  243. }
  244. {
  245. std::string Error;
  246. bool ExecutionFailed;
  247. ProcessInfo PI = ExecuteNoWait(Executable, argv, llvm::None, {}, 0, &Error,
  248. &ExecutionFailed);
  249. ASSERT_EQ(PI.Pid, ProcessInfo::InvalidPid)
  250. << "On error ExecuteNoWait should return an invalid ProcessInfo";
  251. ASSERT_TRUE(ExecutionFailed);
  252. ASSERT_FALSE(Error.empty());
  253. }
  254. }
  255. #ifdef _WIN32
  256. const char utf16le_text[] =
  257. "\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61\x00";
  258. const char utf16be_text[] =
  259. "\x00\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61";
  260. #endif
  261. const char utf8_text[] = "\x6c\x69\x6e\x67\xc3\xbc\x69\xc3\xa7\x61";
  262. TEST(ProgramTest, TestWriteWithSystemEncoding) {
  263. SmallString<128> TestDirectory;
  264. ASSERT_NO_ERROR(fs::createUniqueDirectory("program-test", TestDirectory));
  265. errs() << "Test Directory: " << TestDirectory << '\n';
  266. errs().flush();
  267. SmallString<128> file_pathname(TestDirectory);
  268. path::append(file_pathname, "international-file.txt");
  269. // Only on Windows we should encode in UTF16. For other systems, use UTF8
  270. ASSERT_NO_ERROR(sys::writeFileWithEncoding(file_pathname.c_str(), utf8_text,
  271. sys::WEM_UTF16));
  272. int fd = 0;
  273. ASSERT_NO_ERROR(fs::openFileForRead(file_pathname.c_str(), fd));
  274. #if defined(_WIN32)
  275. char buf[18];
  276. ASSERT_EQ(::read(fd, buf, 18), 18);
  277. if (strncmp(buf, "\xfe\xff", 2) == 0) { // UTF16-BE
  278. ASSERT_EQ(strncmp(&buf[2], utf16be_text, 16), 0);
  279. } else if (strncmp(buf, "\xff\xfe", 2) == 0) { // UTF16-LE
  280. ASSERT_EQ(strncmp(&buf[2], utf16le_text, 16), 0);
  281. } else {
  282. FAIL() << "Invalid BOM in UTF-16 file";
  283. }
  284. #else
  285. char buf[10];
  286. ASSERT_EQ(::read(fd, buf, 10), 10);
  287. ASSERT_EQ(strncmp(buf, utf8_text, 10), 0);
  288. #endif
  289. ::close(fd);
  290. ASSERT_NO_ERROR(fs::remove(file_pathname.str()));
  291. ASSERT_NO_ERROR(fs::remove(TestDirectory.str()));
  292. }
  293. } // end anonymous namespace