clang_runner_test.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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 <string>
  10. #include <utility>
  11. #include "common/check.h"
  12. #include "common/ostream.h"
  13. #include "common/raw_string_ostream.h"
  14. #include "llvm/ADT/ScopeExit.h"
  15. #include "llvm/Object/Binary.h"
  16. #include "llvm/Object/ObjectFile.h"
  17. #include "llvm/Support/FormatVariadic.h"
  18. #include "llvm/Support/Program.h"
  19. #include "llvm/TargetParser/Host.h"
  20. #include "testing/base/capture_std_streams.h"
  21. #include "testing/base/file_helpers.h"
  22. #include "testing/base/global_exe_path.h"
  23. #include "toolchain/driver/llvm_runner.h"
  24. namespace Carbon {
  25. namespace {
  26. using ::testing::Eq;
  27. using ::testing::HasSubstr;
  28. using ::testing::IsSupersetOf;
  29. using ::testing::StrEq;
  30. // NOLINTNEXTLINE(modernize-use-trailing-return-type): Macro based function.
  31. MATCHER_P(TextSymbolNamed, name_matcher, "") {
  32. llvm::Expected<llvm::StringRef> name = arg.getName();
  33. if (auto error = name.takeError()) {
  34. *result_listener << "with an error instead of a name: " << error;
  35. return false;
  36. }
  37. if (!testing::ExplainMatchResult(name_matcher, *name, result_listener)) {
  38. return false;
  39. }
  40. // We have to dig out the section to determine if this was a text symbol.
  41. auto expected_section_it = arg.getSection();
  42. if (auto error = expected_section_it.takeError()) {
  43. *result_listener << "without a section: " << error;
  44. return false;
  45. }
  46. llvm::object::SectionRef section = **expected_section_it;
  47. if (!section.isText()) {
  48. *result_listener << "in the non-text section: " << *section.getName();
  49. return false;
  50. }
  51. return true;
  52. }
  53. class ClangRunnerTest : public ::testing::Test {
  54. public:
  55. InstallPaths install_paths_ =
  56. InstallPaths::MakeForBazelRunfiles(Testing::GetExePath());
  57. Runtimes::Cache runtimes_cache_ =
  58. *Runtimes::Cache::MakeSystem(install_paths_);
  59. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> vfs_ =
  60. llvm::vfs::getRealFileSystem();
  61. };
  62. TEST_F(ClangRunnerTest, Version) {
  63. RawStringOstream test_os;
  64. ClangRunner runner(&install_paths_, vfs_, &test_os);
  65. std::string out;
  66. std::string err;
  67. EXPECT_TRUE(Testing::CallWithCapturedOutput(
  68. out, err, [&] { return runner.RunWithNoRuntimes({"--version"}); }));
  69. // The arguments to Clang should be part of the verbose log.
  70. EXPECT_THAT(test_os.TakeStr(), HasSubstr("--version"));
  71. // No need to flush stderr, just check its contents.
  72. EXPECT_THAT(err, StrEq(""));
  73. // Flush and get the captured stdout to test that this command worked.
  74. // We don't care about any particular version, just that it is printed.
  75. EXPECT_THAT(out, HasSubstr("clang version"));
  76. // The target should match the LLVM default.
  77. EXPECT_THAT(out, HasSubstr((llvm::Twine("Target: ") +
  78. llvm::sys::getDefaultTargetTriple())
  79. .str()));
  80. // Clang's install should be our private LLVM install bin directory.
  81. EXPECT_THAT(out, HasSubstr(std::string("InstalledDir: ") +
  82. install_paths_.llvm_install_bin().native()));
  83. }
  84. TEST_F(ClangRunnerTest, DashC) {
  85. std::filesystem::path test_file =
  86. *Testing::WriteTestFile("test.cpp", "int test() { return 0; }");
  87. std::filesystem::path test_output = *Testing::WriteTestFile("test.o", "");
  88. RawStringOstream verbose_out;
  89. ClangRunner runner(&install_paths_, vfs_, &verbose_out);
  90. std::string out;
  91. std::string err;
  92. EXPECT_TRUE(Testing::CallWithCapturedOutput(
  93. out, err,
  94. [&] {
  95. return runner.RunWithNoRuntimes(
  96. {"-c", test_file.string(), "-o", test_output.string()});
  97. }))
  98. << "Verbose output from runner:\n"
  99. << verbose_out.TakeStr() << "\n";
  100. verbose_out.clear();
  101. // No output should be produced.
  102. EXPECT_THAT(out, StrEq(""));
  103. EXPECT_THAT(err, StrEq(""));
  104. }
  105. TEST_F(ClangRunnerTest, BuitinHeaders) {
  106. std::filesystem::path test_file = *Testing::WriteTestFile("test.c", R"cpp(
  107. #include <stdalign.h>
  108. #ifndef alignas
  109. #error included the wrong header
  110. #endif
  111. )cpp");
  112. std::filesystem::path test_output = *Testing::WriteTestFile("test.o", "");
  113. RawStringOstream verbose_out;
  114. ClangRunner runner(&install_paths_, vfs_, &verbose_out);
  115. std::string out;
  116. std::string err;
  117. EXPECT_TRUE(Testing::CallWithCapturedOutput(
  118. out, err,
  119. [&] {
  120. return runner.RunWithNoRuntimes(
  121. {"-c", test_file.string(), "-o", test_output.string()});
  122. }))
  123. << "Verbose output from runner:\n"
  124. << verbose_out.TakeStr() << "\n";
  125. verbose_out.clear();
  126. // No output should be produced.
  127. EXPECT_THAT(out, StrEq(""));
  128. EXPECT_THAT(err, StrEq(""));
  129. }
  130. TEST_F(ClangRunnerTest, CompileMultipleFiles) {
  131. // Memory leaks and other errors from running Clang can at times only manifest
  132. // with repeated compilations. Use a lambda to just do a series of compiles.
  133. auto compile = [&](llvm::StringRef filename, llvm::StringRef source) {
  134. std::string output_file = std::string(filename.split('.').first) + ".o";
  135. std::filesystem::path file = *Testing::WriteTestFile(filename, source);
  136. std::filesystem::path output = *Testing::WriteTestFile(output_file, "");
  137. RawStringOstream verbose_out;
  138. ClangRunner runner(&install_paths_, vfs_, &verbose_out);
  139. std::string out;
  140. std::string err;
  141. EXPECT_TRUE(Testing::CallWithCapturedOutput(
  142. out, err,
  143. [&] {
  144. return runner.RunWithNoRuntimes(
  145. {"-c", file.string(), "-o", output.string()});
  146. }))
  147. << "Verbose output from runner:\n"
  148. << verbose_out.TakeStr() << "\n";
  149. verbose_out.clear();
  150. EXPECT_THAT(out, StrEq(""));
  151. EXPECT_THAT(err, StrEq(""));
  152. };
  153. compile("test1.cpp", "int test1() { return 0; }");
  154. compile("test2.cpp", "int test2() { return 0; }");
  155. compile("test3.cpp", "int test3() { return 0; }");
  156. }
  157. TEST_F(ClangRunnerTest, BuildResourceDir) {
  158. ClangRunner runner(&install_paths_, vfs_, &llvm::errs());
  159. // Note that we can't test arbitrary targets here as we need to be able to
  160. // compile the builtin functions for the target. We use the default target as
  161. // the most likely to pass.
  162. std::string target = llvm::sys::getDefaultTargetTriple();
  163. llvm::Triple target_triple(target);
  164. Runtimes::Cache::Features features = {.target = target};
  165. auto runtimes = *runtimes_cache_.Lookup(features);
  166. auto tmp_dir = *Filesystem::MakeTmpDir();
  167. llvm::DefaultThreadPool threads(llvm::optimal_concurrency());
  168. auto build_result = runner.BuildTargetResourceDir(
  169. features, runtimes, tmp_dir.abs_path(), threads);
  170. ASSERT_TRUE(build_result.ok()) << build_result.error();
  171. std::filesystem::path resource_dir_path = std::move(*build_result);
  172. // For Linux we can directly check the CRT begin/end object files.
  173. if (target_triple.isOSLinux()) {
  174. std::filesystem::path crt_begin_path =
  175. resource_dir_path / "lib" / target / "clang_rt.crtbegin.o";
  176. ASSERT_TRUE(std::filesystem::is_regular_file(crt_begin_path));
  177. auto begin_result =
  178. llvm::object::ObjectFile::createObjectFile(crt_begin_path.native());
  179. llvm::object::ObjectFile& crtbegin = *begin_result->getBinary();
  180. EXPECT_TRUE(crtbegin.isELF());
  181. EXPECT_TRUE(crtbegin.isObject());
  182. EXPECT_THAT(crtbegin.getArch(), Eq(target_triple.getArch()));
  183. llvm::SmallVector<llvm::object::SymbolRef> symbols(crtbegin.symbols());
  184. // The first symbol should come from the source file.
  185. EXPECT_THAT(*symbols.front().getName(), Eq("crtbegin.c"));
  186. // Check for representative symbols of `crtbegin.o` -- we always use
  187. // `.init_array` in our runtimes build so we have predictable functions.
  188. EXPECT_THAT(symbols, IsSupersetOf({TextSymbolNamed("__do_init"),
  189. TextSymbolNamed("__do_fini")}));
  190. std::filesystem::path crt_end_path =
  191. resource_dir_path / "lib" / target / "clang_rt.crtend.o";
  192. ASSERT_TRUE(std::filesystem::is_regular_file(crt_end_path));
  193. auto end_result =
  194. llvm::object::ObjectFile::createObjectFile(crt_end_path.native());
  195. llvm::object::ObjectFile& crtend = *end_result->getBinary();
  196. EXPECT_TRUE(crtend.isELF());
  197. EXPECT_TRUE(crtend.isObject());
  198. EXPECT_THAT(crtend.getArch(), Eq(target_triple.getArch()));
  199. // Just check the source file symbol, not much of interest in the end.
  200. llvm::object::SymbolRef crtend_front_symbol = *crtend.symbol_begin();
  201. EXPECT_THAT(*crtend_front_symbol.getName(), Eq("crtend.c"));
  202. }
  203. // Across all targets, check that the builtins archive exists, and contains a
  204. // relevant symbol by running the `llvm-nm` tool over it. Using `nm` rather
  205. // than directly inspecting the objects is a bit awkward, but lets us easily
  206. // ignore the wrapping in an archive file.
  207. std::filesystem::path builtins_path =
  208. resource_dir_path / "lib" / target / "libclang_rt.builtins.a";
  209. LLVMRunner llvm_runner(&install_paths_, &llvm::errs());
  210. std::string out;
  211. std::string err;
  212. EXPECT_TRUE(Testing::CallWithCapturedOutput(out, err, [&] {
  213. return llvm_runner.Run(LLVMTool::Nm, {builtins_path.native()});
  214. }));
  215. // Check that we found a definition of `__mulodi4`, a builtin function
  216. // provided by Compiler-RT, but not `libgcc` historically. Note that on macOS
  217. // there is a leading `_` due to mangling.
  218. EXPECT_THAT(out, HasSubstr(target_triple.isMacOSX() ? "T ___mulodi4\n"
  219. : "T __mulodi4\n"));
  220. // Check that we don't include the `chkstk` builtins outside of Windows.
  221. if (!target_triple.isOSWindows()) {
  222. EXPECT_THAT(out, Not(HasSubstr("chkstk")));
  223. }
  224. }
  225. // It's hard to write a portable and reliable unittest for all the layers of the
  226. // Clang driver because they work hard to interact with the underlying
  227. // filesystem and operating system. For now, we just check that a link command
  228. // is echoed back with plausible contents.
  229. //
  230. // TODO: We should eventually strive to have a more complete setup that lets us
  231. // test more complete Clang functionality here.
  232. TEST_F(ClangRunnerTest, LinkCommandEcho) {
  233. // Just create some empty files to use in a synthetic link command below.
  234. std::filesystem::path foo_file = *Testing::WriteTestFile("foo.o", "");
  235. std::filesystem::path bar_file = *Testing::WriteTestFile("bar.o", "");
  236. RawStringOstream verbose_out;
  237. ClangRunner runner(&install_paths_, vfs_, &verbose_out);
  238. std::string out;
  239. std::string err;
  240. EXPECT_TRUE(Testing::CallWithCapturedOutput(
  241. out, err,
  242. [&] {
  243. // Note that we use the target independent run command here because
  244. // we're just getting the echo-ed output back. For this to actually
  245. // link, we'd need to have the target-dependent resources, but those are
  246. // expensive to build so we only want to test them once (above).
  247. return runner.RunWithNoRuntimes(
  248. {"-###", "-o", "binary", foo_file.string(), bar_file.string()});
  249. }))
  250. << "Verbose output from runner:\n"
  251. << verbose_out.TakeStr() << "\n";
  252. verbose_out.clear();
  253. // Because we use `-###' above, we should just see the command that the Clang
  254. // driver would have run in a subprocess. This will be very architecture
  255. // dependent and have lots of variety, but we expect to see both file strings
  256. // in it the command at least.
  257. EXPECT_THAT(err, HasSubstr(foo_file.string())) << err;
  258. EXPECT_THAT(err, HasSubstr(bar_file.string())) << err;
  259. // And no non-stderr output should be produced.
  260. EXPECT_THAT(out, StrEq(""));
  261. }
  262. } // namespace
  263. } // namespace Carbon