cmFindProgramCommand.cxx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. return this->CheckDirectoryForName(path, n);
  72. });
  73. }
  74. bool CheckDirectoryForName(std::string const& path, std::string const& name)
  75. {
  76. return std::any_of(this->Extensions.begin(), this->Extensions.end(),
  77. [this, &path, &name](std::string const& ext) -> bool {
  78. if (!ext.empty() && cmHasSuffix(name, ext)) {
  79. return false;
  80. }
  81. this->TestNameExt = cmStrCat(name, ext);
  82. this->TestPath = cmSystemTools::CollapseFullPath(
  83. this->TestNameExt, path);
  84. bool exists = this->FileIsValid(this->TestPath);
  85. exists ? this->DebugSearches.FoundAt(this->TestPath)
  86. : this->DebugSearches.FailedAt(this->TestPath);
  87. if (exists) {
  88. this->BestPath = this->TestPath;
  89. return true;
  90. }
  91. return false;
  92. });
  93. }
  94. bool FileIsValid(std::string const& file) const
  95. {
  96. if (!this->FileIsExecutableCMP0109(file)) {
  97. return false;
  98. }
  99. #ifdef _WIN32
  100. // Pretend the Windows "python" app installer alias does not exist.
  101. if (cmSystemTools::LowerCase(file).find("/windowsapps/python") !=
  102. std::string::npos) {
  103. std::string dest;
  104. if (cmSystemTools::ReadSymlink(file, dest) &&
  105. cmHasLiteralSuffix(dest, "\\AppInstallerPythonRedirector.exe")) {
  106. return false;
  107. }
  108. }
  109. #endif
  110. return this->FindBase->Validate(file);
  111. }
  112. bool FileIsExecutableCMP0109(std::string const& file) const
  113. {
  114. switch (this->PolicyCMP0109) {
  115. case cmPolicies::OLD:
  116. return cmSystemTools::FileExists(file, true);
  117. case cmPolicies::NEW:
  118. case cmPolicies::REQUIRED_ALWAYS:
  119. case cmPolicies::REQUIRED_IF_USED:
  120. return cmSystemTools::FileIsExecutable(file);
  121. default:
  122. break;
  123. }
  124. bool const isExeOld = cmSystemTools::FileExists(file, true);
  125. bool const isExeNew = cmSystemTools::FileIsExecutable(file);
  126. if (isExeNew == isExeOld) {
  127. return isExeNew;
  128. }
  129. if (isExeNew) {
  130. this->Makefile->IssueMessage(
  131. MessageType::AUTHOR_WARNING,
  132. cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0109),
  133. "\n"
  134. "The file\n"
  135. " ",
  136. file,
  137. "\n"
  138. "is executable but not readable. "
  139. "CMake is ignoring it for compatibility."));
  140. } else {
  141. this->Makefile->IssueMessage(
  142. MessageType::AUTHOR_WARNING,
  143. cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0109),
  144. "\n"
  145. "The file\n"
  146. " ",
  147. file,
  148. "\n"
  149. "is readable but not executable. "
  150. "CMake is using it for compatibility."));
  151. }
  152. return isExeOld;
  153. }
  154. };
  155. cmFindProgramCommand::cmFindProgramCommand(cmExecutionStatus& status)
  156. : cmFindBase("find_program", status)
  157. {
  158. this->NamesPerDirAllowed = true;
  159. this->VariableDocumentation = "Path to a program.";
  160. this->VariableType = cmStateEnums::FILEPATH;
  161. // Windows Registry views
  162. // When policy CMP0134 is not NEW, rely on previous behavior:
  163. if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0134) !=
  164. cmPolicies::NEW) {
  165. if (this->Makefile->GetDefinition("CMAKE_SIZEOF_VOID_P") == "8") {
  166. this->RegistryView = cmWindowsRegistry::View::Reg64_32;
  167. } else {
  168. this->RegistryView = cmWindowsRegistry::View::Reg32_64;
  169. }
  170. } else {
  171. this->RegistryView = cmWindowsRegistry::View::Both;
  172. }
  173. }
  174. // cmFindProgramCommand
  175. bool cmFindProgramCommand::InitialPass(std::vector<std::string> const& argsIn)
  176. {
  177. this->CMakePathName = "PROGRAM";
  178. // call cmFindBase::ParseArguments
  179. if (!this->ParseArguments(argsIn)) {
  180. return false;
  181. }
  182. this->DebugMode = this->ComputeIfDebugModeWanted(this->VariableName);
  183. if (this->AlreadyDefined) {
  184. this->NormalizeFindResult();
  185. return true;
  186. }
  187. std::string const result = this->FindProgram();
  188. this->StoreFindResult(result);
  189. return true;
  190. }
  191. std::string cmFindProgramCommand::FindProgram()
  192. {
  193. std::string program;
  194. if (this->SearchAppBundleFirst || this->SearchAppBundleOnly) {
  195. program = this->FindAppBundle();
  196. }
  197. if (program.empty() && !this->SearchAppBundleOnly) {
  198. program = this->FindNormalProgram();
  199. }
  200. if (program.empty() && this->SearchAppBundleLast) {
  201. program = this->FindAppBundle();
  202. }
  203. return program;
  204. }
  205. std::string cmFindProgramCommand::FindNormalProgram()
  206. {
  207. if (this->NamesPerDir) {
  208. return this->FindNormalProgramNamesPerDir();
  209. }
  210. return this->FindNormalProgramDirsPerName();
  211. }
  212. std::string cmFindProgramCommand::FindNormalProgramNamesPerDir()
  213. {
  214. // Search for all names in each directory.
  215. cmFindProgramHelper helper(this->FindCommandName, this->Makefile, this);
  216. for (std::string const& n : this->Names) {
  217. helper.AddName(n);
  218. }
  219. // Check for the names themselves if they contain a directory separator.
  220. if (helper.CheckCompoundNames()) {
  221. return helper.BestPath;
  222. }
  223. // Search every directory.
  224. for (std::string const& sp : this->SearchPaths) {
  225. if (helper.CheckDirectory(sp)) {
  226. return helper.BestPath;
  227. }
  228. }
  229. // Couldn't find the program.
  230. return "";
  231. }
  232. std::string cmFindProgramCommand::FindNormalProgramDirsPerName()
  233. {
  234. // Search the entire path for each name.
  235. cmFindProgramHelper helper(this->FindCommandName, this->Makefile, this);
  236. for (std::string const& n : this->Names) {
  237. // Switch to searching for this name.
  238. helper.SetName(n);
  239. // Check for the names themselves if they contain a directory separator.
  240. if (helper.CheckCompoundNames()) {
  241. return helper.BestPath;
  242. }
  243. // Search every directory.
  244. for (std::string const& sp : this->SearchPaths) {
  245. if (helper.CheckDirectory(sp)) {
  246. return helper.BestPath;
  247. }
  248. }
  249. }
  250. // Couldn't find the program.
  251. return "";
  252. }
  253. std::string cmFindProgramCommand::FindAppBundle()
  254. {
  255. for (std::string const& name : this->Names) {
  256. std::string appName = name + std::string(".app");
  257. std::string appPath =
  258. cmSystemTools::FindDirectory(appName, this->SearchPaths, true);
  259. if (!appPath.empty()) {
  260. std::string executable = this->GetBundleExecutable(appPath);
  261. if (!executable.empty()) {
  262. return cmSystemTools::CollapseFullPath(executable);
  263. }
  264. }
  265. }
  266. // Couldn't find app bundle
  267. return "";
  268. }
  269. std::string cmFindProgramCommand::GetBundleExecutable(
  270. std::string const& bundlePath)
  271. {
  272. std::string executable;
  273. (void)bundlePath;
  274. #if defined(__APPLE__)
  275. // Started with an example on developer.apple.com about finding bundles
  276. // and modified from that.
  277. // Get a CFString of the app bundle path
  278. // XXX - Is it safe to assume everything is in UTF8?
  279. CFStringRef bundlePathCFS = CFStringCreateWithCString(
  280. kCFAllocatorDefault, bundlePath.c_str(), kCFStringEncodingUTF8);
  281. // Make a CFURLRef from the CFString representation of the
  282. // bundle’s path.
  283. CFURLRef bundleURL = CFURLCreateWithFileSystemPath(
  284. kCFAllocatorDefault, bundlePathCFS, kCFURLPOSIXPathStyle, true);
  285. // Make a bundle instance using the URLRef.
  286. CFBundleRef appBundle = CFBundleCreate(kCFAllocatorDefault, bundleURL);
  287. // returned executableURL is relative to <appbundle>/Contents/MacOS/
  288. CFURLRef executableURL = CFBundleCopyExecutableURL(appBundle);
  289. if (executableURL) {
  290. const int MAX_OSX_PATH_SIZE = 1024;
  291. UInt8 buffer[MAX_OSX_PATH_SIZE];
  292. if (CFURLGetFileSystemRepresentation(executableURL, false, buffer,
  293. MAX_OSX_PATH_SIZE)) {
  294. executable = bundlePath + "/Contents/MacOS/" +
  295. std::string(reinterpret_cast<char*>(buffer));
  296. }
  297. // Only release CFURLRef if it's not null
  298. CFRelease(executableURL);
  299. }
  300. // Any CF objects returned from functions with "create" or
  301. // "copy" in their names must be released by us!
  302. CFRelease(bundlePathCFS);
  303. CFRelease(bundleURL);
  304. CFRelease(appBundle);
  305. #endif
  306. return executable;
  307. }
  308. bool cmFindProgram(std::vector<std::string> const& args,
  309. cmExecutionStatus& status)
  310. {
  311. return cmFindProgramCommand(status).InitialPass(args);
  312. }