ProgramTest.cpp 11 KB

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