cmFindProgramCommand.cxx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmFindProgramCommand.h"
  4. #include <algorithm>
  5. #include <string>
  6. #include <utility>
  7. #include "cmMakefile.h"
  8. #include "cmMessageType.h"
  9. #include "cmPolicies.h"
  10. #include "cmStateTypes.h"
  11. #include "cmStringAlgorithms.h"
  12. #include "cmSystemTools.h"
  13. #include "cmValue.h"
  14. #include "cmWindowsRegistry.h"
  15. class cmExecutionStatus;
  16. #if defined(__APPLE__)
  17. # include <CoreFoundation/CoreFoundation.h>
  18. #endif
  19. struct cmFindProgramHelper
  20. {
  21. cmFindProgramHelper(std::string debugName, cmMakefile* makefile,
  22. cmFindBase const* base)
  23. : DebugSearches(std::move(debugName), base)
  24. , Makefile(makefile)
  25. , FindBase(base)
  26. , PolicyCMP0109(makefile->GetPolicyStatus(cmPolicies::CMP0109))
  27. {
  28. #if defined(_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
  29. // Consider platform-specific extensions.
  30. this->Extensions.push_back(".com");
  31. this->Extensions.push_back(".exe");
  32. #endif
  33. // Consider original name with no extensions.
  34. this->Extensions.emplace_back();
  35. }
  36. // List of valid extensions.
  37. std::vector<std::string> Extensions;
  38. // Keep track of the best program file found so far.
  39. std::string BestPath;
  40. // Current names under consideration.
  41. std::vector<std::string> Names;
  42. // Current name with extension under consideration.
  43. std::string TestNameExt;
  44. // Current full path under consideration.
  45. std::string TestPath;
  46. // Debug state
  47. cmFindBaseDebugState DebugSearches;
  48. cmMakefile* Makefile;
  49. cmFindBase const* FindBase;
  50. cmPolicies::PolicyStatus PolicyCMP0109;
  51. void AddName(std::string const& name) { this->Names.push_back(name); }
  52. void SetName(std::string const& name)
  53. {
  54. this->Names.clear();
  55. this->AddName(name);
  56. }
  57. bool CheckCompoundNames()
  58. {
  59. return std::any_of(this->Names.begin(), this->Names.end(),
  60. [this](std::string const& n) -> bool {
  61. // Only perform search relative to current directory
  62. // if the file name contains a directory separator.
  63. return n.find('/') != std::string::npos &&
  64. this->CheckDirectoryForName("", n);
  65. });
  66. }
  67. bool CheckDirectory(std::string const& path)
  68. {
  69. return std::any_of(this->Names.begin(), this->Names.end(),
  70. [this, &path](std::string const& n) -> bool {
  71. // Only perform search relative to current directory
  72. // if the file name contains a directory separator.
  73. return this->CheckDirectoryForName(path, n);
  74. });
  75. }
  76. bool CheckDirectoryForName(std::string const& path, std::string const& name)
  77. {
  78. return std::any_of(this->Extensions.begin(), this->Extensions.end(),
  79. [this, &path, &name](std::string const& ext) -> bool {
  80. if (!ext.empty() && cmHasSuffix(name, ext)) {
  81. return false;
  82. }
  83. this->TestNameExt = cmStrCat(name, ext);
  84. this->TestPath = cmSystemTools::CollapseFullPath(
  85. this->TestNameExt, path);
  86. bool exists = this->FileIsValid(this->TestPath);
  87. exists ? this->DebugSearches.FoundAt(this->TestPath)
  88. : this->DebugSearches.FailedAt(this->TestPath);
  89. if (exists) {
  90. this->BestPath = this->TestPath;
  91. return true;
  92. }
  93. return false;
  94. });
  95. }
  96. bool FileIsValid(std::string const& file) const
  97. {
  98. if (!this->FileIsExecutableCMP0109(file)) {
  99. return false;
  100. }
  101. #ifdef _WIN32
  102. // Pretend the Windows "python" app installer alias does not exist.
  103. if (cmSystemTools::LowerCase(file).find("/windowsapps/python") !=
  104. std::string::npos) {
  105. std::string dest;
  106. if (cmSystemTools::ReadSymlink(file, dest) &&
  107. cmHasLiteralSuffix(dest, "\\AppInstallerPythonRedirector.exe")) {
  108. return false;
  109. }
  110. }
  111. #endif
  112. return this->FindBase->Validate(file);
  113. }
  114. bool FileIsExecutableCMP0109(std::string const& file) const
  115. {
  116. switch (this->PolicyCMP0109) {
  117. case cmPolicies::OLD:
  118. return cmSystemTools::FileExists(file, true);
  119. case cmPolicies::NEW:
  120. case cmPolicies::REQUIRED_ALWAYS:
  121. case cmPolicies::REQUIRED_IF_USED:
  122. return cmSystemTools::FileIsExecutable(file);
  123. default:
  124. break;
  125. }
  126. bool const isExeOld = cmSystemTools::FileExists(file, true);
  127. bool const isExeNew = cmSystemTools::FileIsExecutable(file);
  128. if (isExeNew == isExeOld) {
  129. return isExeNew;
  130. }
  131. if (isExeNew) {
  132. this->Makefile->IssueMessage(
  133. MessageType::AUTHOR_WARNING,
  134. cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0109),
  135. "\n"
  136. "The file\n"
  137. " ",
  138. file,
  139. "\n"
  140. "is executable but not readable. "
  141. "CMake is ignoring it for compatibility."));
  142. } else {
  143. this->Makefile->IssueMessage(
  144. MessageType::AUTHOR_WARNING,
  145. cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0109),
  146. "\n"
  147. "The file\n"
  148. " ",
  149. file,
  150. "\n"
  151. "is readable but not executable. "
  152. "CMake is using it for compatibility."));
  153. }
  154. return isExeOld;
  155. }
  156. };
  157. cmFindProgramCommand::cmFindProgramCommand(cmExecutionStatus& status)
  158. : cmFindBase("find_program", status)
  159. {
  160. this->NamesPerDirAllowed = true;
  161. this->VariableDocumentation = "Path to a program.";
  162. this->VariableType = cmStateEnums::FILEPATH;
  163. // Windows Registry views
  164. // When policy CMP0134 is not NEW, rely on previous behavior:
  165. if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0134) !=
  166. cmPolicies::NEW) {
  167. if (this->Makefile->GetDefinition("CMAKE_SIZEOF_VOID_P") == "8") {
  168. this->RegistryView = cmWindowsRegistry::View::Reg64_32;
  169. } else {
  170. this->RegistryView = cmWindowsRegistry::View::Reg32_64;
  171. }
  172. } else {
  173. this->RegistryView = cmWindowsRegistry::View::Both;
  174. }
  175. }
  176. // cmFindProgramCommand
  177. bool cmFindProgramCommand::InitialPass(std::vector<std::string> const& argsIn)
  178. {
  179. this->CMakePathName = "PROGRAM";
  180. // call cmFindBase::ParseArguments
  181. if (!this->ParseArguments(argsIn)) {
  182. return false;
  183. }
  184. this->DebugMode = this->ComputeIfDebugModeWanted(this->VariableName);
  185. if (this->AlreadyDefined) {
  186. this->NormalizeFindResult();
  187. return true;
  188. }
  189. std::string const result = this->FindProgram();
  190. this->StoreFindResult(result);
  191. return true;
  192. }
  193. std::string cmFindProgramCommand::FindProgram()
  194. {
  195. std::string program;
  196. if (this->SearchAppBundleFirst || this->SearchAppBundleOnly) {
  197. program = this->FindAppBundle();
  198. }
  199. if (program.empty() && !this->SearchAppBundleOnly) {
  200. program = this->FindNormalProgram();
  201. }
  202. if (program.empty() && this->SearchAppBundleLast) {
  203. program = this->FindAppBundle();
  204. }
  205. return program;
  206. }
  207. std::string cmFindProgramCommand::FindNormalProgram()
  208. {
  209. if (this->NamesPerDir) {
  210. return this->FindNormalProgramNamesPerDir();
  211. }
  212. return this->FindNormalProgramDirsPerName();
  213. }
  214. std::string cmFindProgramCommand::FindNormalProgramNamesPerDir()
  215. {
  216. // Search for all names in each directory.
  217. cmFindProgramHelper helper(this->FindCommandName, this->Makefile, this);
  218. for (std::string const& n : this->Names) {
  219. helper.AddName(n);
  220. }
  221. // Check for the names themselves if they contain a directory separator.
  222. if (helper.CheckCompoundNames()) {
  223. return helper.BestPath;
  224. }
  225. // Search every directory.
  226. for (std::string const& sp : this->SearchPaths) {
  227. if (helper.CheckDirectory(sp)) {
  228. return helper.BestPath;
  229. }
  230. }
  231. // Couldn't find the program.
  232. return "";
  233. }
  234. std::string cmFindProgramCommand::FindNormalProgramDirsPerName()
  235. {
  236. // Search the entire path for each name.
  237. cmFindProgramHelper helper(this->FindCommandName, this->Makefile, this);
  238. for (std::string const& n : this->Names) {
  239. // Switch to searching for this name.
  240. helper.SetName(n);
  241. // Check for the names themselves if they contain a directory separator.
  242. if (helper.CheckCompoundNames()) {
  243. return helper.BestPath;
  244. }
  245. // Search every directory.
  246. for (std::string const& sp : this->SearchPaths) {
  247. if (helper.CheckDirectory(sp)) {
  248. return helper.BestPath;
  249. }
  250. }
  251. }
  252. // Couldn't find the program.
  253. return "";
  254. }
  255. std::string cmFindProgramCommand::FindAppBundle()
  256. {
  257. for (std::string const& name : this->Names) {
  258. std::string appName = name + std::string(".app");
  259. std::string appPath =
  260. cmSystemTools::FindDirectory(appName, this->SearchPaths, true);
  261. if (!appPath.empty()) {
  262. std::string executable = this->GetBundleExecutable(appPath);
  263. if (!executable.empty()) {
  264. return cmSystemTools::CollapseFullPath(executable);
  265. }
  266. }
  267. }
  268. // Couldn't find app bundle
  269. return "";
  270. }
  271. std::string cmFindProgramCommand::GetBundleExecutable(
  272. std::string const& bundlePath)
  273. {
  274. std::string executable;
  275. (void)bundlePath;
  276. #if defined(__APPLE__)
  277. // Started with an example on developer.apple.com about finding bundles
  278. // and modified from that.
  279. // Get a CFString of the app bundle path
  280. // XXX - Is it safe to assume everything is in UTF8?
  281. CFStringRef bundlePathCFS = CFStringCreateWithCString(
  282. kCFAllocatorDefault, bundlePath.c_str(), kCFStringEncodingUTF8);
  283. // Make a CFURLRef from the CFString representation of the
  284. // bundle’s path.
  285. CFURLRef bundleURL = CFURLCreateWithFileSystemPath(
  286. kCFAllocatorDefault, bundlePathCFS, kCFURLPOSIXPathStyle, true);
  287. // Make a bundle instance using the URLRef.
  288. CFBundleRef appBundle = CFBundleCreate(kCFAllocatorDefault, bundleURL);
  289. // returned executableURL is relative to <appbundle>/Contents/MacOS/
  290. CFURLRef executableURL = CFBundleCopyExecutableURL(appBundle);
  291. if (executableURL) {
  292. const int MAX_OSX_PATH_SIZE = 1024;
  293. UInt8 buffer[MAX_OSX_PATH_SIZE];
  294. if (CFURLGetFileSystemRepresentation(executableURL, false, buffer,
  295. MAX_OSX_PATH_SIZE)) {
  296. executable = bundlePath + "/Contents/MacOS/" +
  297. std::string(reinterpret_cast<char*>(buffer));
  298. }
  299. // Only release CFURLRef if it's not null
  300. CFRelease(executableURL);
  301. }
  302. // Any CF objects returned from functions with "create" or
  303. // "copy" in their names must be released by us!
  304. CFRelease(bundlePathCFS);
  305. CFRelease(bundleURL);
  306. CFRelease(appBundle);
  307. #endif
  308. return executable;
  309. }
  310. bool cmFindProgram(std::vector<std::string> const& args,
  311. cmExecutionStatus& status)
  312. {
  313. return cmFindProgramCommand(status).InitialPass(args);
  314. }