clang_runtimes_test.cpp 13 KB

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