exe_path.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 "common/exe_path.h"
  5. #include <optional>
  6. #include <string>
  7. #include <utility>
  8. #include "llvm/ADT/StringRef.h"
  9. #include "llvm/Support/FileSystem.h"
  10. #include "llvm/Support/Program.h"
  11. namespace Carbon {
  12. // Returns true if a found path resolves to the actual executable path.
  13. static auto RealPathMatches(const char* found_path, llvm::StringRef exe_path)
  14. -> bool {
  15. char* buffer = realpath(found_path, nullptr);
  16. if (!buffer) {
  17. return false;
  18. }
  19. bool matches = exe_path == buffer;
  20. free(buffer);
  21. return matches;
  22. }
  23. auto FindExecutablePath(const char* argv0) -> std::string {
  24. static int static_for_main_addr;
  25. // Note this returns the canonical path, dropping symlink information that we
  26. // might want. As a consequence, we use it as a last resort. However, it's
  27. // also helpful to use to ensure we found the correct tool through other
  28. // means.
  29. std::string exe_path =
  30. llvm::sys::fs::getMainExecutable(argv0, &static_for_main_addr);
  31. llvm::StringRef argv0_ref = argv0;
  32. // If `argv[0]` is path-like and points at the executable, use the form in
  33. // `argv[0]`.
  34. if (argv0_ref.contains('/') && RealPathMatches(argv0, exe_path)) {
  35. return argv0_ref.str();
  36. }
  37. // If we can find `argv[0]` in `$PATH`, use the form from that.
  38. //
  39. // For example, `llvm-symbolizer` is subprocessed with `argv[0]` that uses
  40. // this path. If `LLVM_SYMBOLIZER_PATH` is set to Carbon, but
  41. // `llvm-symbolizer` in `$PATH` is a different binary, that can lead to
  42. // problems -- which is why we verify the match.
  43. if (llvm::ErrorOr<std::string> path = llvm::sys::findProgramByName(argv0_ref);
  44. path && RealPathMatches(path->c_str(), exe_path)) {
  45. return std::move(*path);
  46. }
  47. // As a fallback, use exe_path.
  48. return exe_path;
  49. }
  50. } // namespace Carbon