clang_runner_test.cpp 11 KB

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