clang_runtimes_test.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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_runtimes.h"
  5. #include <gmock/gmock.h>
  6. #include <gtest/gtest.h>
  7. #include <filesystem>
  8. #include <string>
  9. #include <utility>
  10. #include "common/check.h"
  11. #include "common/ostream.h"
  12. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  13. #include "llvm/ADT/SmallVector.h"
  14. #include "llvm/Object/Binary.h"
  15. #include "llvm/Object/ObjectFile.h"
  16. #include "llvm/Support/ThreadPool.h"
  17. #include "llvm/Support/Threading.h"
  18. #include "llvm/Support/VirtualFileSystem.h"
  19. #include "llvm/TargetParser/Host.h"
  20. #include "llvm/TargetParser/Triple.h"
  21. #include "testing/base/capture_std_streams.h"
  22. #include "testing/base/global_exe_path.h"
  23. #include "toolchain/base/install_paths.h"
  24. #include "toolchain/base/llvm_tools.h"
  25. #include "toolchain/driver/clang_runner.h"
  26. #include "toolchain/driver/llvm_runner.h"
  27. #include "toolchain/driver/runtimes_cache.h"
  28. namespace Carbon {
  29. namespace {
  30. using ::testing::Eq;
  31. using ::testing::HasSubstr;
  32. using ::testing::IsSupersetOf;
  33. // NOLINTNEXTLINE(modernize-use-trailing-return-type): Macro based function.
  34. MATCHER_P(TextSymbolNamed, name_matcher, "") {
  35. llvm::Expected<llvm::StringRef> name = arg.getName();
  36. if (auto error = name.takeError()) {
  37. *result_listener << "with an error instead of a name: " << error;
  38. return false;
  39. }
  40. if (!testing::ExplainMatchResult(name_matcher, *name, result_listener)) {
  41. return false;
  42. }
  43. // We have to dig out the section to determine if this was a text symbol.
  44. auto expected_section_it = arg.getSection();
  45. if (auto error = expected_section_it.takeError()) {
  46. *result_listener << "without a section: " << error;
  47. return false;
  48. }
  49. llvm::object::SectionRef section = **expected_section_it;
  50. if (!section.isText()) {
  51. *result_listener << "in the non-text section: " << *section.getName();
  52. return false;
  53. }
  54. return true;
  55. }
  56. class ClangRuntimesTest : public ::testing::Test {
  57. public:
  58. // Helper to get the `llvm-nm` listing of defined symbols for an archive.
  59. //
  60. // TODO: It would be nice to use a library API and matchers instead of
  61. // `llvm-nm` and matching text on the output.
  62. auto NmListDefinedSymbols(const std::filesystem::path& archive)
  63. -> std::string {
  64. LLVMRunner llvm_runner(&install_paths_, &llvm::errs());
  65. std::string out;
  66. std::string err;
  67. bool result = Testing::CallWithCapturedOutput(out, err, [&] {
  68. return llvm_runner.Run(
  69. LLVMTool::Nm, {"--format=just-symbols", "--defined-only", "--quiet",
  70. archive.native()});
  71. });
  72. CARBON_CHECK(result, "Unable to run `llvm-nm`:\n{1}", err);
  73. return out;
  74. }
  75. // Helper to expect a specific symbol in the `llvm-nm` list.
  76. //
  77. // This handles platform-specific formatting of symbols.
  78. auto ExpectSymbol(llvm::StringRef nm_list, llvm::StringRef symbol) -> void {
  79. std::string symbol_substr = llvm::formatv(
  80. target_triple_.isMacOSX() ? "\n_{0}\n" : "\n{0}\n", symbol);
  81. // Do the actual match with `HasSubstr` so it can explain failures.
  82. EXPECT_THAT(nm_list, HasSubstr(symbol_substr));
  83. }
  84. InstallPaths install_paths_ =
  85. InstallPaths::MakeForBazelRunfiles(Testing::GetExePath());
  86. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> vfs_ =
  87. llvm::vfs::getRealFileSystem();
  88. // Note that for debugging, you can pass `llvm::errs()` as the vlog stream,
  89. // but this makes the output both very verbose and hard to use with multiple
  90. // threads.
  91. ClangRunner runner_{&install_paths_, vfs_};
  92. // Note that we can't test arbitrary targets here as we need to be able to
  93. // compile the builtin functions for the target. We use the default target as
  94. // the most likely to pass.
  95. std::string target_ = llvm::sys::getDefaultTargetTriple();
  96. llvm::Triple target_triple_{target_};
  97. Runtimes::Cache runtimes_cache_ =
  98. *Runtimes::Cache::MakeSystem(install_paths_);
  99. Runtimes::Cache::Features features = {.target = target_};
  100. Runtimes runtimes_ = *runtimes_cache_.Lookup(features);
  101. // Note that for debugging it may be useful to replace this with a
  102. // single-threaded thread pool. However the test will be _much_ slower.
  103. llvm::DefaultThreadPool threads_{llvm::optimal_concurrency()};
  104. };
  105. TEST_F(ClangRuntimesTest, ResourceDir) {
  106. ClangResourceDirBuilder resource_dir_builder(&runner_, &threads_,
  107. target_triple_, &runtimes_);
  108. auto build_result = std::move(resource_dir_builder).Wait();
  109. ASSERT_TRUE(build_result.ok()) << build_result.error();
  110. std::filesystem::path resource_dir_path = std::move(*build_result);
  111. // For Linux we can directly check the CRT begin/end object files.
  112. if (target_triple_.isOSLinux()) {
  113. std::filesystem::path crt_begin_path =
  114. resource_dir_path / "lib" / target_ / "clang_rt.crtbegin.o";
  115. ASSERT_TRUE(std::filesystem::is_regular_file(crt_begin_path));
  116. auto begin_result =
  117. llvm::object::ObjectFile::createObjectFile(crt_begin_path.native());
  118. llvm::object::ObjectFile& crtbegin = *begin_result->getBinary();
  119. EXPECT_TRUE(crtbegin.isELF());
  120. EXPECT_TRUE(crtbegin.isObject());
  121. EXPECT_THAT(crtbegin.getArch(), Eq(target_triple_.getArch()));
  122. llvm::SmallVector<llvm::object::SymbolRef> symbols(crtbegin.symbols());
  123. // The first symbol should come from the source file.
  124. EXPECT_THAT(*symbols.front().getName(), Eq("crtbegin.c"));
  125. // Check for representative symbols of `crtbegin.o` -- we always use
  126. // `.init_array` in our runtimes build so we have predictable functions.
  127. EXPECT_THAT(symbols, IsSupersetOf({TextSymbolNamed("__do_init"),
  128. TextSymbolNamed("__do_fini")}));
  129. std::filesystem::path crt_end_path =
  130. resource_dir_path / "lib" / target_ / "clang_rt.crtend.o";
  131. ASSERT_TRUE(std::filesystem::is_regular_file(crt_end_path));
  132. auto end_result =
  133. llvm::object::ObjectFile::createObjectFile(crt_end_path.native());
  134. llvm::object::ObjectFile& crtend = *end_result->getBinary();
  135. EXPECT_TRUE(crtend.isELF());
  136. EXPECT_TRUE(crtend.isObject());
  137. EXPECT_THAT(crtend.getArch(), Eq(target_triple_.getArch()));
  138. // Just check the source file symbol, not much of interest in the end.
  139. llvm::object::SymbolRef crtend_front_symbol = *crtend.symbol_begin();
  140. EXPECT_THAT(*crtend_front_symbol.getName(), Eq("crtend.c"));
  141. }
  142. // Across all targets, check that the builtins archive exists, and contains a
  143. // relevant symbol by running the `llvm-nm` tool over it. Using `nm` rather
  144. // than directly inspecting the objects is a bit awkward, but lets us easily
  145. // ignore the wrapping in an archive file.
  146. std::filesystem::path builtins_path =
  147. resource_dir_path / "lib" / target_ / "libclang_rt.builtins.a";
  148. std::string builtins_symbols = NmListDefinedSymbols(builtins_path);
  149. // Check that we found a definition of `__mulodi4`, a builtin function
  150. // provided by Compiler-RT.
  151. ExpectSymbol(builtins_symbols, "__mulodi4");
  152. // Check that we don't include the `chkstk` builtins outside of Windows.
  153. if (!target_triple_.isOSWindows()) {
  154. EXPECT_THAT(builtins_symbols, Not(HasSubstr("chkstk")));
  155. }
  156. }
  157. TEST_F(ClangRuntimesTest, Libunwind) {
  158. LibunwindBuilder libunwind_builder(&runner_, &threads_, target_triple_,
  159. &runtimes_);
  160. auto build_result = std::move(libunwind_builder).Wait();
  161. ASSERT_TRUE(build_result.ok()) << build_result.error();
  162. std::filesystem::path runtimes_path = std::move(*build_result);
  163. std::filesystem::path libunwind_path = runtimes_path / "lib/libunwind.a";
  164. std::string libunwind_symbols = NmListDefinedSymbols(libunwind_path);
  165. // Check a few of the main exported symbols here. The set here is somewhat
  166. // arbitrary, but chosen to be among the more stable names and have at least
  167. // one from most of the object files that should be linked into the archive.
  168. ExpectSymbol(libunwind_symbols, "_Unwind_Resume");
  169. ExpectSymbol(libunwind_symbols, "_Unwind_Backtrace");
  170. ExpectSymbol(libunwind_symbols, "__unw_getcontext");
  171. ExpectSymbol(libunwind_symbols, "__unw_get_proc_info");
  172. }
  173. TEST_F(ClangRuntimesTest, Libcxx) {
  174. #if __has_feature(address_sanitizer)
  175. // ASan causes Clang and LLVM to be _egregiously_ inefficient at compiling
  176. // libc++, taking 5x - 10x longer than without ASan. Rough estimate is that it
  177. // would take 5-10 minutes on GitHub's Linux runner. Given the limited utility
  178. // of this test coverage, skip it in that configuration. This also misses
  179. // assert-coverage for building libc++, but we don't really expect issues
  180. // there. Misconfiguration and other common issues should still be covered in
  181. // fully optimized builds at much lower cost.
  182. GTEST_SKIP() << "Skipping build of libc++ with an ASan-itized Clang";
  183. #endif
  184. LibcxxBuilder libcxx_builder(&runner_, &threads_, target_triple_, &runtimes_);
  185. auto build_result = std::move(libcxx_builder).Wait();
  186. ASSERT_TRUE(build_result.ok()) << build_result.error();
  187. std::filesystem::path runtimes_path = std::move(*build_result);
  188. std::filesystem::path libcxx_path = runtimes_path / "lib/libc++.a";
  189. std::string libcxx_symbols = NmListDefinedSymbols(libcxx_path);
  190. // First check a few fundamental symbols from libc++.a, including symbols both
  191. // within the ABI namespace and outside of it.
  192. ExpectSymbol(libcxx_symbols, "_ZNKSt12bad_any_cast4whatEv");
  193. ExpectSymbol(libcxx_symbols, "_ZNSt2_C8to_charsEPcS0_d");
  194. ExpectSymbol(libcxx_symbols, "_ZSt17current_exceptionv");
  195. ExpectSymbol(libcxx_symbols, "_ZNKSt2_C10filesystem4path10__filenameEv");
  196. // Check that several of the libc++abi object files are also included in the
  197. // archive.
  198. ExpectSymbol(libcxx_symbols, "__cxa_bad_cast");
  199. ExpectSymbol(libcxx_symbols, "__cxa_new_handler");
  200. ExpectSymbol(libcxx_symbols, "__cxa_demangle");
  201. ExpectSymbol(libcxx_symbols, "__cxa_get_globals");
  202. ExpectSymbol(libcxx_symbols, "_ZSt9terminatev");
  203. }
  204. } // namespace
  205. } // namespace Carbon