clang_runner_test.cpp 7.2 KB

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