clang_runtimes_test.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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 <memory>
  9. #include <string>
  10. #include <utility>
  11. #include "common/check.h"
  12. #include "common/ostream.h"
  13. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  14. #include "llvm/ADT/SmallVector.h"
  15. #include "llvm/Object/Binary.h"
  16. #include "llvm/Object/ObjectFile.h"
  17. #include "llvm/Support/ThreadPool.h"
  18. #include "llvm/Support/Threading.h"
  19. #include "llvm/Support/VirtualFileSystem.h"
  20. #include "llvm/TargetParser/Host.h"
  21. #include "llvm/TargetParser/Triple.h"
  22. #include "testing/base/capture_std_streams.h"
  23. #include "testing/base/global_exe_path.h"
  24. #include "toolchain/base/install_paths.h"
  25. #include "toolchain/base/llvm_tools.h"
  26. #include "toolchain/driver/clang_runner.h"
  27. #include "toolchain/driver/llvm_runner.h"
  28. #include "toolchain/driver/runtimes_cache.h"
  29. #include "tools/cpp/runfiles/runfiles.h"
  30. namespace Carbon {
  31. namespace {
  32. using ::bazel::tools::cpp::runfiles::Runfiles;
  33. using ::testing::Each;
  34. using ::testing::Eq;
  35. using ::testing::HasSubstr;
  36. using ::testing::IsSupersetOf;
  37. // NOLINTNEXTLINE(modernize-use-trailing-return-type): Macro based function.
  38. MATCHER_P(TextSymbolNamed, name_matcher, "") {
  39. llvm::Expected<llvm::StringRef> name = arg.getName();
  40. if (auto error = name.takeError()) {
  41. *result_listener << "with an error instead of a name: " << error;
  42. return false;
  43. }
  44. if (!testing::ExplainMatchResult(name_matcher, *name, result_listener)) {
  45. return false;
  46. }
  47. // We have to dig out the section to determine if this was a text symbol.
  48. auto expected_section_it = arg.getSection();
  49. if (auto error = expected_section_it.takeError()) {
  50. *result_listener << "without a section: " << error;
  51. return false;
  52. }
  53. llvm::object::SectionRef section = **expected_section_it;
  54. if (!section.isText()) {
  55. *result_listener << "in the non-text section: " << *section.getName();
  56. return false;
  57. }
  58. return true;
  59. }
  60. // NOLINTNEXTLINE(modernize-use-trailing-return-type): Macro based function.
  61. MATCHER(IsBasename, "") {
  62. std::filesystem::path path = arg;
  63. return path == path.filename();
  64. }
  65. class ClangRuntimesTest : public ::testing::Test {
  66. public:
  67. ClangRuntimesTest() {
  68. std::string error;
  69. test_runfiles_.reset(Runfiles::Create(exe_path_, &error));
  70. CARBON_CHECK(test_runfiles_ != nullptr, "{0}", error);
  71. }
  72. // Helper to get the `llvm-nm` listing of defined symbols for an archive.
  73. //
  74. // TODO: It would be nice to use a library API and matchers instead of
  75. // `llvm-nm` and matching text on the output.
  76. auto NmListDefinedSymbols(const std::filesystem::path& archive)
  77. -> std::string {
  78. LLVMRunner llvm_runner(&install_paths_, &llvm::errs());
  79. std::string out;
  80. std::string err;
  81. bool result = Testing::CallWithCapturedOutput(out, err, [&] {
  82. return llvm_runner.Run(
  83. LLVMTool::Nm, {"--format=just-symbols", "--defined-only", "--quiet",
  84. archive.native()});
  85. });
  86. CARBON_CHECK(result, "Unable to run `llvm-nm`:\n{0}", err);
  87. return out;
  88. }
  89. // Helper to expect a specific symbol in the `llvm-nm` list.
  90. //
  91. // This handles platform-specific formatting of symbols.
  92. auto ExpectSymbol(llvm::StringRef nm_list, llvm::StringRef symbol) -> void {
  93. std::string symbol_substr = llvm::formatv(
  94. target_triple_.isMacOSX() ? "\n_{0}\n" : "\n{0}\n", symbol);
  95. // Do the actual match with `HasSubstr` so it can explain failures.
  96. EXPECT_THAT(nm_list, HasSubstr(symbol_substr));
  97. }
  98. // Helper to get the names of archive members.
  99. auto ListArchiveMemberNames(const std::filesystem::path& archive_path)
  100. -> llvm::SmallVector<std::string> {
  101. llvm::SmallVector<std::string> result;
  102. auto archive_buffer_result =
  103. llvm::MemoryBuffer::getFile(archive_path.native());
  104. CARBON_CHECK(!archive_buffer_result.getError(), "Unable to open {0}: {1}",
  105. archive_path, archive_buffer_result.getError().message());
  106. auto archive = llvm::cantFail(llvm::object::Archive::create(
  107. archive_buffer_result.get()->getMemBufferRef()));
  108. llvm::Error error = llvm::Error::success();
  109. for (const auto& child : archive->children(error)) {
  110. result.push_back(child.getName()->str());
  111. }
  112. CARBON_CHECK(!error, "Error reading members of archive {0}: {1}",
  113. archive_path, error);
  114. return result;
  115. }
  116. auto TestResourceDir(std::filesystem::path resource_dir_path) -> void {
  117. // For Linux we can directly check the CRT begin/end object files.
  118. if (target_triple_.isOSLinux()) {
  119. std::filesystem::path crt_begin_path =
  120. resource_dir_path / "lib" / target_ / "clang_rt.crtbegin.o";
  121. ASSERT_TRUE(std::filesystem::is_regular_file(crt_begin_path));
  122. auto begin_result =
  123. llvm::object::ObjectFile::createObjectFile(crt_begin_path.native());
  124. llvm::object::ObjectFile& crtbegin = *begin_result->getBinary();
  125. EXPECT_TRUE(crtbegin.isELF());
  126. EXPECT_TRUE(crtbegin.isObject());
  127. EXPECT_THAT(crtbegin.getArch(), Eq(target_triple_.getArch()));
  128. llvm::SmallVector<llvm::object::SymbolRef> symbols(crtbegin.symbols());
  129. // The first symbol should come from the source file.
  130. EXPECT_THAT(*symbols.front().getName(), Eq("crtbegin.c"));
  131. // Check for representative symbols of `crtbegin.o` -- we always use
  132. // `.init_array` in our runtimes build so we have predictable functions.
  133. EXPECT_THAT(symbols, IsSupersetOf({TextSymbolNamed("__do_init"),
  134. TextSymbolNamed("__do_fini")}));
  135. std::filesystem::path crt_end_path =
  136. resource_dir_path / "lib" / target_ / "clang_rt.crtend.o";
  137. ASSERT_TRUE(std::filesystem::is_regular_file(crt_end_path));
  138. auto end_result =
  139. llvm::object::ObjectFile::createObjectFile(crt_end_path.native());
  140. llvm::object::ObjectFile& crtend = *end_result->getBinary();
  141. EXPECT_TRUE(crtend.isELF());
  142. EXPECT_TRUE(crtend.isObject());
  143. EXPECT_THAT(crtend.getArch(), Eq(target_triple_.getArch()));
  144. // Just check the source file symbol, not much of interest in the end.
  145. llvm::object::SymbolRef crtend_front_symbol = *crtend.symbol_begin();
  146. EXPECT_THAT(*crtend_front_symbol.getName(), Eq("crtend.c"));
  147. }
  148. // Across all targets, check that the builtins archive exists, and contains
  149. // a relevant symbol by running the `llvm-nm` tool over it. Using `nm`
  150. // rather than directly inspecting the objects is a bit awkward, but lets us
  151. // easily ignore the wrapping in an archive file.
  152. std::filesystem::path builtins_path =
  153. resource_dir_path / "lib" / target_ / "libclang_rt.builtins.a";
  154. std::string builtins_symbols = NmListDefinedSymbols(builtins_path);
  155. // Check that we found a definition of `__mulodi4`, a builtin function
  156. // provided by Compiler-RT.
  157. ExpectSymbol(builtins_symbols, "__mulodi4");
  158. // Check that we don't include the `chkstk` builtins outside of Windows.
  159. if (!target_triple_.isOSWindows()) {
  160. EXPECT_THAT(builtins_symbols, Not(HasSubstr("chkstk")));
  161. }
  162. // Check that member names don't contain full paths, as that is the
  163. // canonical format produced by `ar`.
  164. auto member_names = ListArchiveMemberNames(builtins_path);
  165. EXPECT_THAT(member_names, Each(IsBasename()));
  166. }
  167. auto TestLibunwind(std::filesystem::path libunwind_path) -> void {
  168. std::string libunwind_symbols = NmListDefinedSymbols(libunwind_path);
  169. // Check a few of the main exported symbols here. The set here is somewhat
  170. // arbitrary, but chosen to be among the more stable names and have at least
  171. // one from most of the object files that should be linked into the archive.
  172. ExpectSymbol(libunwind_symbols, "_Unwind_Resume");
  173. ExpectSymbol(libunwind_symbols, "_Unwind_Backtrace");
  174. ExpectSymbol(libunwind_symbols, "__unw_getcontext");
  175. ExpectSymbol(libunwind_symbols, "__unw_get_proc_info");
  176. // Check that member names don't contain full paths, as that is the
  177. // canonical format produced by `ar`.
  178. auto member_names = ListArchiveMemberNames(libunwind_path);
  179. EXPECT_THAT(member_names, Each(IsBasename()));
  180. }
  181. auto TestLibcxx(std::filesystem::path libcxx_path) -> void {
  182. std::string libcxx_symbols = NmListDefinedSymbols(libcxx_path);
  183. // First check a few fundamental symbols from libc++.a, including symbols
  184. // both within the ABI namespace and outside of it.
  185. ExpectSymbol(libcxx_symbols, "_ZNKSt12bad_any_cast4whatEv");
  186. ExpectSymbol(libcxx_symbols, "_ZNSt2_C8to_charsEPcS0_d");
  187. ExpectSymbol(libcxx_symbols, "_ZSt17current_exceptionv");
  188. ExpectSymbol(libcxx_symbols, "_ZNKSt2_C10filesystem4path10__filenameEv");
  189. // Check that several of the libc++abi object files are also included in the
  190. // archive.
  191. ExpectSymbol(libcxx_symbols, "__cxa_bad_cast");
  192. ExpectSymbol(libcxx_symbols, "__cxa_new_handler");
  193. ExpectSymbol(libcxx_symbols, "__cxa_demangle");
  194. ExpectSymbol(libcxx_symbols, "__cxa_get_globals");
  195. ExpectSymbol(libcxx_symbols, "_ZSt9terminatev");
  196. // Check that member names don't contain full paths, as that is the
  197. // canonical format produced by `ar`.
  198. auto member_names = ListArchiveMemberNames(libcxx_path);
  199. EXPECT_THAT(member_names, Each(IsBasename()));
  200. }
  201. std::string exe_path_ = Testing::GetExePath().str();
  202. std::unique_ptr<Runfiles> test_runfiles_;
  203. InstallPaths install_paths_ = InstallPaths::MakeForBazelRunfiles(exe_path_);
  204. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> vfs_ =
  205. llvm::vfs::getRealFileSystem();
  206. // Note that for debugging, you can pass `llvm::errs()` as the vlog stream,
  207. // but this makes the output both very verbose and hard to use with multiple
  208. // threads.
  209. ClangRunner runner_{&install_paths_, vfs_};
  210. // Note that we can't test arbitrary targets here as we need to be able to
  211. // compile the builtin functions for the target. We use the default target as
  212. // the most likely to pass.
  213. std::string target_ = llvm::sys::getDefaultTargetTriple();
  214. llvm::Triple target_triple_{target_};
  215. Runtimes::Cache runtimes_cache_ =
  216. *Runtimes::Cache::MakeSystem(install_paths_);
  217. Runtimes::Cache::Features features = {.target = target_};
  218. Runtimes runtimes_ = *runtimes_cache_.Lookup(features);
  219. // Note that for debugging it may be useful to replace this with a
  220. // single-threaded thread pool. However the test will be _much_ slower.
  221. llvm::DefaultThreadPool threads_{llvm::optimal_concurrency()};
  222. };
  223. TEST_F(ClangRuntimesTest, ResourceDir) {
  224. ClangResourceDirBuilder resource_dir_builder(&runner_, &threads_,
  225. target_triple_, &runtimes_);
  226. auto build_result = std::move(resource_dir_builder).Wait();
  227. ASSERT_TRUE(build_result.ok()) << build_result.error();
  228. TestResourceDir(std::move(*build_result));
  229. }
  230. TEST_F(ClangRuntimesTest, Libunwind) {
  231. LibunwindBuilder libunwind_builder(&runner_, &threads_, target_triple_,
  232. &runtimes_);
  233. auto build_result = std::move(libunwind_builder).Wait();
  234. ASSERT_TRUE(build_result.ok()) << build_result.error();
  235. std::filesystem::path runtimes_path = std::move(*build_result);
  236. TestLibunwind(runtimes_path / "lib/libunwind.a");
  237. }
  238. // ASan causes Clang and LLVM to be _egregiously_ inefficient at compiling
  239. // libc++, taking 5x - 10x longer than without ASan. Rough estimate is that it
  240. // would take 5-10 minutes on GitHub's Linux runner.
  241. //
  242. // We test libc++ in the prebuilt runtimes below in a more cache friendly and
  243. // sustainable way. Given that, we disable this test by default but include it
  244. // for debugging purposes.
  245. TEST_F(ClangRuntimesTest, DISABLED_Libcxx) {
  246. LibcxxBuilder libcxx_builder(&runner_, &threads_, target_triple_, &runtimes_);
  247. auto build_result = std::move(libcxx_builder).Wait();
  248. ASSERT_TRUE(build_result.ok()) << build_result.error();
  249. std::filesystem::path runtimes_path = std::move(*build_result);
  250. TestLibcxx(runtimes_path / "lib/libc++.a");
  251. }
  252. TEST_F(ClangRuntimesTest, PrebuiltResourceDir) {
  253. std::filesystem::path prebuilt_runtimes_path = test_runfiles_->Rlocation(
  254. "carbon/toolchain/driver/prebuilt_runtimes_tree");
  255. TestResourceDir(prebuilt_runtimes_path / "clang_resource_dir");
  256. }
  257. TEST_F(ClangRuntimesTest, PrebuiltLibunwind) {
  258. std::filesystem::path prebuilt_runtimes_path = test_runfiles_->Rlocation(
  259. "carbon/toolchain/driver/prebuilt_runtimes_tree");
  260. TestLibunwind(prebuilt_runtimes_path / "libunwind/lib/libunwind.a");
  261. }
  262. TEST_F(ClangRuntimesTest, PrebuiltLibcxx) {
  263. std::filesystem::path prebuilt_runtimes_path = test_runfiles_->Rlocation(
  264. "carbon/toolchain/driver/prebuilt_runtimes_tree");
  265. TestLibcxx(prebuilt_runtimes_path / "libcxx/lib/libc++.a");
  266. }
  267. } // namespace
  268. } // namespace Carbon