cmFindProgramCommand.cxx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. class cmExecutionStatus;
  14. #if defined(__APPLE__)
  15. # include <CoreFoundation/CoreFoundation.h>
  16. #endif
  17. struct cmFindProgramHelper
  18. {
  19. cmFindProgramHelper(std::string debugName, cmMakefile* makefile,
  20. cmFindBase const* base)
  21. : DebugSearches(std::move(debugName), base)
  22. , Makefile(makefile)
  23. , PolicyCMP0109(makefile->GetPolicyStatus(cmPolicies::CMP0109))
  24. {
  25. #if defined(_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
  26. // Consider platform-specific extensions.
  27. this->Extensions.push_back(".com");
  28. this->Extensions.push_back(".exe");
  29. #endif
  30. // Consider original name with no extensions.
  31. this->Extensions.emplace_back();
  32. }
  33. // List of valid extensions.
  34. std::vector<std::string> Extensions;
  35. // Keep track of the best program file found so far.
  36. std::string BestPath;
  37. // Current names under consideration.
  38. std::vector<std::string> Names;
  39. // Current name with extension under consideration.
  40. std::string TestNameExt;
  41. // Current full path under consideration.
  42. std::string TestPath;
  43. // Debug state
  44. cmFindBaseDebugState DebugSearches;
  45. cmMakefile* Makefile;
  46. cmPolicies::PolicyStatus PolicyCMP0109;
  47. void AddName(std::string const& name) { this->Names.push_back(name); }
  48. void SetName(std::string const& name)
  49. {
  50. this->Names.clear();
  51. this->AddName(name);
  52. }
  53. bool CheckCompoundNames()
  54. {
  55. return std::any_of(this->Names.begin(), this->Names.end(),
  56. [this](std::string const& n) -> bool {
  57. // Only perform search relative to current directory
  58. // if the file name contains a directory separator.
  59. return n.find('/') != std::string::npos &&
  60. this->CheckDirectoryForName("", n);
  61. });
  62. }
  63. bool CheckDirectory(std::string const& path)
  64. {
  65. return std::any_of(this->Names.begin(), this->Names.end(),
  66. [this, &path](std::string const& n) -> bool {
  67. // Only perform search relative to current directory
  68. // if the file name contains a directory separator.
  69. return this->CheckDirectoryForName(path, n);
  70. });
  71. }
  72. bool CheckDirectoryForName(std::string const& path, std::string const& name)
  73. {
  74. return std::any_of(this->Extensions.begin(), this->Extensions.end(),
  75. [this, &path, &name](std::string const& ext) -> bool {
  76. if (!ext.empty() && cmHasSuffix(name, ext)) {
  77. return false;
  78. }
  79. this->TestNameExt = cmStrCat(name, ext);
  80. this->TestPath = cmSystemTools::CollapseFullPath(
  81. this->TestNameExt, path);
  82. bool exists = this->FileIsExecutable(this->TestPath);
  83. exists ? this->DebugSearches.FoundAt(this->TestPath)
  84. : this->DebugSearches.FailedAt(this->TestPath);
  85. if (exists) {
  86. this->BestPath = this->TestPath;
  87. return true;
  88. }
  89. return false;
  90. });
  91. }
  92. bool FileIsExecutable(std::string const& file) const
  93. {
  94. #ifdef _WIN32
  95. if (!this->FileIsExecutableCMP0109(file)) {
  96. return false;
  97. }
  98. // Pretend the Windows "python" app installer alias does not exist.
  99. if (cmSystemTools::LowerCase(file).find("/windowsapps/python") !=
  100. std::string::npos) {
  101. std::string dest;
  102. if (cmSystemTools::ReadSymlink(file, dest) &&
  103. cmHasLiteralSuffix(dest, "\\AppInstallerPythonRedirector.exe")) {
  104. return false;
  105. }
  106. }
  107. return true;
  108. #else
  109. return this->FileIsExecutableCMP0109(file);
  110. #endif
  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. }
  162. // cmFindProgramCommand
  163. bool cmFindProgramCommand::InitialPass(std::vector<std::string> const& argsIn)
  164. {
  165. this->CMakePathName = "PROGRAM";
  166. // call cmFindBase::ParseArguments
  167. if (!this->ParseArguments(argsIn)) {
  168. return false;
  169. }
  170. this->DebugMode = this->ComputeIfDebugModeWanted(this->VariableName);
  171. if (this->AlreadyDefined) {
  172. this->NormalizeFindResult();
  173. return true;
  174. }
  175. std::string const result = this->FindProgram();
  176. this->StoreFindResult(result);
  177. return true;
  178. }
  179. std::string cmFindProgramCommand::FindProgram()
  180. {
  181. std::string program;
  182. if (this->SearchAppBundleFirst || this->SearchAppBundleOnly) {
  183. program = this->FindAppBundle();
  184. }
  185. if (program.empty() && !this->SearchAppBundleOnly) {
  186. program = this->FindNormalProgram();
  187. }
  188. if (program.empty() && this->SearchAppBundleLast) {
  189. program = this->FindAppBundle();
  190. }
  191. return program;
  192. }
  193. std::string cmFindProgramCommand::FindNormalProgram()
  194. {
  195. if (this->NamesPerDir) {
  196. return this->FindNormalProgramNamesPerDir();
  197. }
  198. return this->FindNormalProgramDirsPerName();
  199. }
  200. std::string cmFindProgramCommand::FindNormalProgramNamesPerDir()
  201. {
  202. // Search for all names in each directory.
  203. cmFindProgramHelper helper(this->FindCommandName, this->Makefile, this);
  204. for (std::string const& n : this->Names) {
  205. helper.AddName(n);
  206. }
  207. // Check for the names themselves if they contain a directory separator.
  208. if (helper.CheckCompoundNames()) {
  209. return helper.BestPath;
  210. }
  211. // Search every directory.
  212. for (std::string const& sp : this->SearchPaths) {
  213. if (helper.CheckDirectory(sp)) {
  214. return helper.BestPath;
  215. }
  216. }
  217. // Couldn't find the program.
  218. return "";
  219. }
  220. std::string cmFindProgramCommand::FindNormalProgramDirsPerName()
  221. {
  222. // Search the entire path for each name.
  223. cmFindProgramHelper helper(this->FindCommandName, this->Makefile, this);
  224. for (std::string const& n : this->Names) {
  225. // Switch to searching for this name.
  226. helper.SetName(n);
  227. // Check for the names themselves if they contain a directory separator.
  228. if (helper.CheckCompoundNames()) {
  229. return helper.BestPath;
  230. }
  231. // Search every directory.
  232. for (std::string const& sp : this->SearchPaths) {
  233. if (helper.CheckDirectory(sp)) {
  234. return helper.BestPath;
  235. }
  236. }
  237. }
  238. // Couldn't find the program.
  239. return "";
  240. }
  241. std::string cmFindProgramCommand::FindAppBundle()
  242. {
  243. for (std::string const& name : this->Names) {
  244. std::string appName = name + std::string(".app");
  245. std::string appPath =
  246. cmSystemTools::FindDirectory(appName, this->SearchPaths, true);
  247. if (!appPath.empty()) {
  248. std::string executable = this->GetBundleExecutable(appPath);
  249. if (!executable.empty()) {
  250. return cmSystemTools::CollapseFullPath(executable);
  251. }
  252. }
  253. }
  254. // Couldn't find app bundle
  255. return "";
  256. }
  257. std::string cmFindProgramCommand::GetBundleExecutable(
  258. std::string const& bundlePath)
  259. {
  260. std::string executable;
  261. (void)bundlePath;
  262. #if defined(__APPLE__)
  263. // Started with an example on developer.apple.com about finding bundles
  264. // and modified from that.
  265. // Get a CFString of the app bundle path
  266. // XXX - Is it safe to assume everything is in UTF8?
  267. CFStringRef bundlePathCFS = CFStringCreateWithCString(
  268. kCFAllocatorDefault, bundlePath.c_str(), kCFStringEncodingUTF8);
  269. // Make a CFURLRef from the CFString representation of the
  270. // bundle’s path.
  271. CFURLRef bundleURL = CFURLCreateWithFileSystemPath(
  272. kCFAllocatorDefault, bundlePathCFS, kCFURLPOSIXPathStyle, true);
  273. // Make a bundle instance using the URLRef.
  274. CFBundleRef appBundle = CFBundleCreate(kCFAllocatorDefault, bundleURL);
  275. // returned executableURL is relative to <appbundle>/Contents/MacOS/
  276. CFURLRef executableURL = CFBundleCopyExecutableURL(appBundle);
  277. if (executableURL != nullptr) {
  278. const int MAX_OSX_PATH_SIZE = 1024;
  279. UInt8 buffer[MAX_OSX_PATH_SIZE];
  280. if (CFURLGetFileSystemRepresentation(executableURL, false, buffer,
  281. MAX_OSX_PATH_SIZE)) {
  282. executable = bundlePath + "/Contents/MacOS/" +
  283. std::string(reinterpret_cast<char*>(buffer));
  284. }
  285. // Only release CFURLRef if it's not null
  286. CFRelease(executableURL);
  287. }
  288. // Any CF objects returned from functions with "create" or
  289. // "copy" in their names must be released by us!
  290. CFRelease(bundlePathCFS);
  291. CFRelease(bundleURL);
  292. CFRelease(appBundle);
  293. #endif
  294. return executable;
  295. }
  296. bool cmFindProgram(std::vector<std::string> const& args,
  297. cmExecutionStatus& status)
  298. {
  299. return cmFindProgramCommand(status).InitialPass(args);
  300. }