clang_runner_test.cpp 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/driver/clang_runner.h"
  5. #include <gmock/gmock.h>
  6. #include <gtest/gtest.h>
  7. #include <filesystem>
  8. #include <fstream>
  9. #include <utility>
  10. #include "common/check.h"
  11. #include "common/ostream.h"
  12. #include "common/raw_string_ostream.h"
  13. #include "llvm/ADT/ScopeExit.h"
  14. #include "llvm/Object/Binary.h"
  15. #include "llvm/Support/FormatVariadic.h"
  16. #include "llvm/Support/Program.h"
  17. #include "llvm/TargetParser/Host.h"
  18. #include "testing/base/global_exe_path.h"
  19. namespace Carbon {
  20. namespace {
  21. using ::testing::HasSubstr;
  22. using ::testing::StrEq;
  23. // While these are marked as "internal" APIs, they seem to work and be pretty
  24. // widely used for their exact documented behavior.
  25. using ::testing::internal::CaptureStderr;
  26. using ::testing::internal::CaptureStdout;
  27. using ::testing::internal::GetCapturedStderr;
  28. using ::testing::internal::GetCapturedStdout;
  29. // Calls the provided lambda with `stderr` and `stdout` captured and saved into
  30. // the provided output parameters. The lambda's result is returned. It is
  31. // important to not put anything inside the lambda whose output would be useful
  32. // in interpreting test errors such as Google Test assertions as their output
  33. // will end up captured as well.
  34. template <typename CallableT>
  35. static auto RunWithCapturedOutput(std::string& out, std::string& err,
  36. CallableT callable) {
  37. CaptureStderr();
  38. CaptureStdout();
  39. auto result = callable();
  40. // No need to flush stderr.
  41. err = GetCapturedStderr();
  42. llvm::outs().flush();
  43. out = GetCapturedStdout();
  44. return result;
  45. }
  46. TEST(ClangRunnerTest, Version) {
  47. RawStringOstream test_os;
  48. const auto install_paths =
  49. InstallPaths::MakeForBazelRunfiles(Testing::GetExePath());
  50. std::string target = llvm::sys::getDefaultTargetTriple();
  51. auto vfs = llvm::vfs::getRealFileSystem();
  52. ClangRunner runner(&install_paths, target, vfs, &test_os);
  53. std::string out;
  54. std::string err;
  55. EXPECT_TRUE(RunWithCapturedOutput(out, err,
  56. [&] { return runner.Run({"--version"}); }));
  57. // The arguments to Clang should be part of the verbose log.
  58. EXPECT_THAT(test_os.TakeStr(), HasSubstr("--version"));
  59. // No need to flush stderr, just check its contents.
  60. EXPECT_THAT(err, StrEq(""));
  61. // Flush and get the captured stdout to test that this command worked.
  62. // We don't care about any particular version, just that it is printed.
  63. EXPECT_THAT(out, HasSubstr("clang version"));
  64. // The target should match what we provided.
  65. EXPECT_THAT(out, HasSubstr((llvm::Twine("Target: ") + target).str()));
  66. // Clang's install should be our private LLVM install bin directory.
  67. EXPECT_THAT(out, HasSubstr(std::string("InstalledDir: ") +
  68. install_paths.llvm_install_bin()));
  69. }
  70. // Utility to write a test file. We don't need the full power provided here yet,
  71. // but we anticipate adding more tests such as compiling basic C++ code in the
  72. // future and this provides a basis for building those tests.
  73. static auto WriteTestFile(llvm::StringRef name_suffix, llvm::Twine contents)
  74. -> std::filesystem::path {
  75. std::filesystem::path test_tmpdir;
  76. if (char* tmpdir_env = getenv("TEST_TMPDIR"); tmpdir_env != nullptr) {
  77. test_tmpdir = std::string(tmpdir_env);
  78. } else {
  79. test_tmpdir = std::filesystem::temp_directory_path();
  80. }
  81. const auto* unit_test = ::testing::UnitTest::GetInstance();
  82. const auto* test_info = unit_test->current_test_info();
  83. std::filesystem::path test_file =
  84. test_tmpdir / llvm::formatv("{0}_{1}_{2}", test_info->test_suite_name(),
  85. test_info->name(), name_suffix)
  86. .str();
  87. // Make debugging a bit easier by cleaning up any files from previous runs.
  88. // This is only necessary when not run in Bazel's test environment.
  89. std::filesystem::remove(test_file);
  90. CARBON_CHECK(!std::filesystem::exists(test_file));
  91. {
  92. std::error_code ec;
  93. llvm::raw_fd_ostream test_file_stream(test_file.string(), ec);
  94. CARBON_CHECK(!ec, "Test file error: {0}", ec.message());
  95. test_file_stream << contents;
  96. }
  97. return test_file;
  98. }
  99. // It's hard to write a portable and reliable unittest for all the layers of the
  100. // Clang driver because they work hard to interact with the underlying
  101. // filesystem and operating system. For now, we just check that a link command
  102. // is echoed back with plausible contents.
  103. //
  104. // TODO: We should eventually strive to have a more complete setup that lets us
  105. // test more complete Clang functionality here.
  106. TEST(ClangRunnerTest, LinkCommandEcho) {
  107. // Just create some empty files to use in a synthetic link command below.
  108. std::filesystem::path foo_file = WriteTestFile("foo.o", "");
  109. std::filesystem::path bar_file = WriteTestFile("bar.o", "");
  110. const auto install_paths =
  111. InstallPaths::MakeForBazelRunfiles(Testing::GetExePath());
  112. RawStringOstream verbose_out;
  113. std::string target = llvm::sys::getDefaultTargetTriple();
  114. auto vfs = llvm::vfs::getRealFileSystem();
  115. ClangRunner runner(&install_paths, target, vfs, &verbose_out);
  116. std::string out;
  117. std::string err;
  118. EXPECT_TRUE(RunWithCapturedOutput(out, err,
  119. [&] {
  120. return runner.Run({"-###", "-o", "binary",
  121. foo_file.string(),
  122. bar_file.string()});
  123. }))
  124. << "Verbose output from runner:\n"
  125. << verbose_out.TakeStr() << "\n";
  126. verbose_out.clear();
  127. // Because we use `-###' above, we should just see the command that the Clang
  128. // driver would have run in a subprocess. This will be very architecture
  129. // dependent and have lots of variety, but we expect to see both file strings
  130. // in it the command at least.
  131. EXPECT_THAT(err, HasSubstr(foo_file.string())) << err;
  132. EXPECT_THAT(err, HasSubstr(bar_file.string())) << err;
  133. // And no non-stderr output should be produced.
  134. EXPECT_THAT(out, StrEq(""));
  135. }
  136. TEST(ClangRunnerTest, DashC) {
  137. std::filesystem::path test_file =
  138. WriteTestFile("test.cpp", "int test() { return 0; }");
  139. std::filesystem::path test_output = WriteTestFile("test.o", "");
  140. const auto install_paths =
  141. InstallPaths::MakeForBazelRunfiles(Testing::GetExePath());
  142. RawStringOstream verbose_out;
  143. std::string target = llvm::sys::getDefaultTargetTriple();
  144. auto vfs = llvm::vfs::getRealFileSystem();
  145. ClangRunner runner(&install_paths, target, vfs, &verbose_out);
  146. std::string out;
  147. std::string err;
  148. EXPECT_TRUE(RunWithCapturedOutput(out, err,
  149. [&] {
  150. return runner.Run(
  151. {"-c", test_file.string(), "-o",
  152. test_output.string()});
  153. }))
  154. << "Verbose output from runner:\n"
  155. << verbose_out.TakeStr() << "\n";
  156. verbose_out.clear();
  157. // No output should be produced.
  158. EXPECT_THAT(out, StrEq(""));
  159. EXPECT_THAT(err, StrEq(""));
  160. }
  161. } // namespace
  162. } // namespace Carbon