cmFindBase.cxx 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. #include "cmFindBase.h"
  4. #include <algorithm>
  5. #include <cstddef>
  6. #include <deque>
  7. #include <iterator>
  8. #include <map>
  9. #include <utility>
  10. #include <cm/optional>
  11. #include <cmext/algorithm>
  12. #include <cmext/string_view>
  13. #include "cmCMakePath.h"
  14. #include "cmConfigureLog.h"
  15. #include "cmExecutionStatus.h"
  16. #include "cmList.h"
  17. #include "cmListFileCache.h"
  18. #include "cmMakefile.h"
  19. #include "cmMessageType.h"
  20. #include "cmPolicies.h"
  21. #include "cmRange.h"
  22. #include "cmSearchPath.h"
  23. #include "cmState.h"
  24. #include "cmStateTypes.h"
  25. #include "cmStringAlgorithms.h"
  26. #include "cmSystemTools.h"
  27. #include "cmValue.h"
  28. #include "cmWindowsRegistry.h"
  29. #include "cmake.h"
  30. cmFindBase::cmFindBase(std::string findCommandName, cmExecutionStatus& status)
  31. : cmFindCommon(status)
  32. , FindCommandName(std::move(findCommandName))
  33. {
  34. }
  35. bool cmFindBase::ParseArguments(std::vector<std::string> const& argsIn)
  36. {
  37. if (argsIn.size() < 2) {
  38. this->SetError("called with incorrect number of arguments");
  39. return false;
  40. }
  41. // copy argsIn into args so it can be modified,
  42. // in the process extract the DOC "documentation"
  43. // and handle options NO_CACHE and ENV
  44. size_t size = argsIn.size();
  45. std::vector<std::string> args;
  46. bool foundDoc = false;
  47. for (unsigned int j = 0; j < size; ++j) {
  48. if (foundDoc || argsIn[j] != "DOC") {
  49. if (argsIn[j] == "NO_CACHE") {
  50. this->StoreResultInCache = false;
  51. } else if (argsIn[j] == "ENV") {
  52. if (j + 1 < size) {
  53. j++;
  54. std::vector<std::string> p =
  55. cmSystemTools::GetEnvPathNormalized(argsIn[j]);
  56. std::move(p.begin(), p.end(), std::back_inserter(args));
  57. }
  58. } else {
  59. args.push_back(argsIn[j]);
  60. }
  61. } else {
  62. if (j + 1 < size) {
  63. foundDoc = true;
  64. this->VariableDocumentation = argsIn[j + 1];
  65. j++;
  66. if (j >= size) {
  67. break;
  68. }
  69. }
  70. }
  71. }
  72. if (args.size() < 2) {
  73. this->SetError("called with incorrect number of arguments");
  74. return false;
  75. }
  76. this->VariableName = args[0];
  77. this->InitialState = this->GetInitialState();
  78. if (this->IsFound()) {
  79. return true;
  80. }
  81. // Find what search path locations have been enabled/disable
  82. this->SelectDefaultSearchModes();
  83. // Find the current root path mode.
  84. this->SelectDefaultRootPathMode();
  85. // Find the current bundle/framework search policy.
  86. this->SelectDefaultMacMode();
  87. bool newStyle = false;
  88. bool haveRequiredOrOptional = false;
  89. enum Doing
  90. {
  91. DoingNone,
  92. DoingNames,
  93. DoingPaths,
  94. DoingPathSuffixes,
  95. DoingHints
  96. };
  97. Doing doing = DoingNames; // assume it starts with a name
  98. for (unsigned int j = 1; j < args.size(); ++j) {
  99. if (args[j] == "NAMES") {
  100. doing = DoingNames;
  101. newStyle = true;
  102. } else if (args[j] == "PATHS") {
  103. doing = DoingPaths;
  104. newStyle = true;
  105. } else if (args[j] == "HINTS") {
  106. doing = DoingHints;
  107. newStyle = true;
  108. } else if (args[j] == "PATH_SUFFIXES") {
  109. doing = DoingPathSuffixes;
  110. newStyle = true;
  111. } else if (args[j] == "NAMES_PER_DIR") {
  112. doing = DoingNone;
  113. if (this->NamesPerDirAllowed) {
  114. this->NamesPerDir = true;
  115. } else {
  116. this->SetError("does not support NAMES_PER_DIR");
  117. return false;
  118. }
  119. } else if (args[j] == "NO_SYSTEM_PATH") {
  120. doing = DoingNone;
  121. this->NoDefaultPath = true;
  122. } else if (args[j] == "REQUIRED") {
  123. doing = DoingNone;
  124. if (haveRequiredOrOptional && !this->Required) {
  125. this->SetError("cannot be both REQUIRED and OPTIONAL");
  126. return false;
  127. }
  128. this->Required = true;
  129. newStyle = true;
  130. haveRequiredOrOptional = true;
  131. } else if (args[j] == "OPTIONAL") {
  132. doing = DoingNone;
  133. if (haveRequiredOrOptional && this->Required) {
  134. this->SetError("cannot be both REQUIRED and OPTIONAL");
  135. return false;
  136. }
  137. newStyle = true;
  138. haveRequiredOrOptional = true;
  139. } else if (args[j] == "REGISTRY_VIEW") {
  140. if (++j == args.size()) {
  141. this->SetError("missing required argument for REGISTRY_VIEW");
  142. return false;
  143. }
  144. auto view = cmWindowsRegistry::ToView(args[j]);
  145. if (view) {
  146. this->RegistryView = *view;
  147. } else {
  148. this->SetError(
  149. cmStrCat("given invalid value for REGISTRY_VIEW: ", args[j]));
  150. return false;
  151. }
  152. } else if (args[j] == "VALIDATOR") {
  153. if (++j == args.size()) {
  154. this->SetError("missing required argument for VALIDATOR");
  155. return false;
  156. }
  157. auto command = this->Makefile->GetState()->GetCommand(args[j]);
  158. if (!command) {
  159. this->SetError(cmStrCat(
  160. "command specified for VALIDATOR is undefined: ", args[j], '.'));
  161. return false;
  162. }
  163. // ensure a macro is not specified as validator
  164. auto const& validatorName = args[j];
  165. cmList macros{ this->Makefile->GetProperty("MACROS") };
  166. if (std::find_if(macros.begin(), macros.end(),
  167. [&validatorName](std::string const& item) {
  168. return cmSystemTools::Strucmp(validatorName.c_str(),
  169. item.c_str()) == 0;
  170. }) != macros.end()) {
  171. this->SetError(cmStrCat(
  172. "command specified for VALIDATOR is not a function: ", args[j],
  173. '.'));
  174. return false;
  175. }
  176. this->ValidatorName = args[j];
  177. } else if (this->CheckCommonArgument(args[j])) {
  178. doing = DoingNone;
  179. } else {
  180. // Some common arguments were accidentally supported by CMake
  181. // 2.4 and 2.6.0 in the short-hand form of the command, so we
  182. // must support it even though it is not documented.
  183. if (doing == DoingNames) {
  184. this->Names.push_back(args[j]);
  185. } else if (doing == DoingPaths) {
  186. this->UserGuessArgs.push_back(args[j]);
  187. } else if (doing == DoingHints) {
  188. this->UserHintsArgs.push_back(args[j]);
  189. } else if (doing == DoingPathSuffixes) {
  190. this->AddPathSuffix(args[j]);
  191. }
  192. }
  193. }
  194. if (!haveRequiredOrOptional) {
  195. this->Required = this->Makefile->IsOn("CMAKE_FIND_REQUIRED");
  196. }
  197. if (this->VariableDocumentation.empty()) {
  198. this->VariableDocumentation = "Where can ";
  199. if (this->Names.empty()) {
  200. this->VariableDocumentation += "the (unknown) library be found";
  201. } else if (this->Names.size() == 1) {
  202. this->VariableDocumentation +=
  203. "the " + this->Names.front() + " library be found";
  204. } else {
  205. this->VariableDocumentation += "one of the ";
  206. this->VariableDocumentation +=
  207. cmJoin(cmMakeRange(this->Names).retreat(1), ", ");
  208. this->VariableDocumentation +=
  209. " or " + this->Names.back() + " libraries be found";
  210. }
  211. }
  212. // look for old style
  213. // FIND_*(VAR name path1 path2 ...)
  214. if (!newStyle && !this->Names.empty()) {
  215. // All the short-hand arguments have been recorded as names.
  216. std::vector<std::string> shortArgs = this->Names;
  217. this->Names.clear(); // clear out any values in Names
  218. this->Names.push_back(shortArgs[0]);
  219. cm::append(this->UserGuessArgs, shortArgs.begin() + 1, shortArgs.end());
  220. }
  221. this->ExpandPaths();
  222. this->ComputeFinalPaths(IgnorePaths::Yes);
  223. return true;
  224. }
  225. bool cmFindBase::Validate(std::string const& path) const
  226. {
  227. if (this->ValidatorName.empty()) {
  228. return true;
  229. }
  230. // The validator command will be executed in an isolated scope.
  231. cmMakefile::ScopePushPop varScope(this->Makefile);
  232. cmMakefile::PolicyPushPop polScope(this->Makefile);
  233. static_cast<void>(varScope);
  234. static_cast<void>(polScope);
  235. auto resultName =
  236. cmStrCat("CMAKE_"_s, cmSystemTools::UpperCase(this->FindCommandName),
  237. "_VALIDATOR_STATUS"_s);
  238. this->Makefile->AddDefinitionBool(resultName, true);
  239. cmListFileFunction validator(
  240. this->ValidatorName, 0, 0,
  241. { cmListFileArgument(resultName, cmListFileArgument::Unquoted, 0),
  242. cmListFileArgument(path, cmListFileArgument::Quoted, 0) });
  243. cmExecutionStatus status(*this->Makefile);
  244. if (this->Makefile->ExecuteCommand(validator, status)) {
  245. return this->Makefile->GetDefinition(resultName).IsOn();
  246. }
  247. return false;
  248. }
  249. void cmFindBase::ExpandPaths()
  250. {
  251. if (!this->NoDefaultPath) {
  252. if (!this->NoPackageRootPath) {
  253. this->FillPackageRootPath();
  254. }
  255. if (!this->NoCMakePath) {
  256. this->FillCMakeVariablePath();
  257. }
  258. if (!this->NoCMakeEnvironmentPath) {
  259. this->FillCMakeEnvironmentPath();
  260. }
  261. }
  262. this->FillUserHintsPath();
  263. if (!this->NoDefaultPath) {
  264. if (!this->NoSystemEnvironmentPath) {
  265. this->FillSystemEnvironmentPath();
  266. }
  267. if (!this->NoCMakeSystemPath) {
  268. this->FillCMakeSystemVariablePath();
  269. }
  270. }
  271. this->FillUserGuessPath();
  272. }
  273. void cmFindBase::FillCMakeEnvironmentPath()
  274. {
  275. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeEnvironment];
  276. // Add CMAKE_*_PATH environment variables
  277. std::string var = cmStrCat("CMAKE_", this->CMakePathName, "_PATH");
  278. paths.AddEnvPrefixPath("CMAKE_PREFIX_PATH");
  279. paths.AddEnvPath(var);
  280. if (this->CMakePathName == "PROGRAM") {
  281. paths.AddEnvPath("CMAKE_APPBUNDLE_PATH");
  282. } else {
  283. paths.AddEnvPath("CMAKE_FRAMEWORK_PATH");
  284. }
  285. paths.AddSuffixes(this->SearchPathSuffixes);
  286. }
  287. void cmFindBase::FillPackageRootPath()
  288. {
  289. cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRoot];
  290. // Add the PACKAGE_ROOT_PATH from each enclosing find_package call.
  291. for (std::vector<std::string> const& pkgPaths :
  292. cmReverseRange(this->Makefile->FindPackageRootPathStack)) {
  293. paths.AddPrefixPaths(pkgPaths);
  294. }
  295. paths.AddSuffixes(this->SearchPathSuffixes);
  296. }
  297. void cmFindBase::FillCMakeVariablePath()
  298. {
  299. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMake];
  300. // Add CMake variables of the same name as the previous environment
  301. // variables CMAKE_*_PATH to be used most of the time with -D
  302. // command line options
  303. std::string var = cmStrCat("CMAKE_", this->CMakePathName, "_PATH");
  304. paths.AddCMakePrefixPath("CMAKE_PREFIX_PATH");
  305. paths.AddCMakePath(var);
  306. if (this->CMakePathName == "PROGRAM") {
  307. paths.AddCMakePath("CMAKE_APPBUNDLE_PATH");
  308. } else {
  309. paths.AddCMakePath("CMAKE_FRAMEWORK_PATH");
  310. }
  311. paths.AddSuffixes(this->SearchPathSuffixes);
  312. }
  313. void cmFindBase::FillSystemEnvironmentPath()
  314. {
  315. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemEnvironment];
  316. // Add LIB or INCLUDE
  317. if (!this->EnvironmentPath.empty()) {
  318. paths.AddEnvPath(this->EnvironmentPath);
  319. }
  320. // Add PATH
  321. paths.AddEnvPath("PATH");
  322. paths.AddSuffixes(this->SearchPathSuffixes);
  323. }
  324. namespace {
  325. struct entry_to_remove
  326. {
  327. entry_to_remove(std::string const& name, cmMakefile* makefile)
  328. {
  329. if (cmValue to_skip = makefile->GetDefinition(
  330. cmStrCat("_CMAKE_SYSTEM_PREFIX_PATH_", name, "_PREFIX_COUNT"))) {
  331. cmStrToLong(*to_skip, &count);
  332. }
  333. if (cmValue prefix_value = makefile->GetDefinition(
  334. cmStrCat("_CMAKE_SYSTEM_PREFIX_PATH_", name, "_PREFIX_VALUE"))) {
  335. value = *prefix_value;
  336. }
  337. }
  338. bool valid() const { return count > 0 && !value.empty(); }
  339. void remove_self(std::vector<std::string>& entries) const
  340. {
  341. if (this->valid()) {
  342. long to_skip = this->count;
  343. size_t index_to_remove = 0;
  344. for (auto const& path : entries) {
  345. if (path == this->value && --to_skip == 0) {
  346. break;
  347. }
  348. ++index_to_remove;
  349. }
  350. if (index_to_remove < entries.size() && to_skip == 0) {
  351. entries.erase(entries.begin() + index_to_remove);
  352. }
  353. }
  354. }
  355. long count = -1;
  356. std::string value;
  357. };
  358. }
  359. void cmFindBase::FillCMakeSystemVariablePath()
  360. {
  361. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeSystem];
  362. bool const install_prefix_in_list =
  363. !this->Makefile->IsOn("CMAKE_FIND_NO_INSTALL_PREFIX");
  364. bool const remove_install_prefix = this->NoCMakeInstallPath;
  365. bool const add_install_prefix = !this->NoCMakeInstallPath &&
  366. this->Makefile->IsDefinitionSet("CMAKE_FIND_USE_INSTALL_PREFIX");
  367. // We have 3 possible states for `CMAKE_SYSTEM_PREFIX_PATH` and
  368. // `CMAKE_INSTALL_PREFIX`.
  369. // Either we need to remove `CMAKE_INSTALL_PREFIX`, add
  370. // `CMAKE_INSTALL_PREFIX`, or do nothing.
  371. //
  372. // When we need to remove `CMAKE_INSTALL_PREFIX` we remove the Nth occurrence
  373. // of `CMAKE_INSTALL_PREFIX` from `CMAKE_SYSTEM_PREFIX_PATH`, where `N` is
  374. // computed by `CMakeSystemSpecificInformation.cmake` while constructing
  375. // `CMAKE_SYSTEM_PREFIX_PATH`. This ensures that if projects / toolchains
  376. // have removed `CMAKE_INSTALL_PREFIX` from the list, we don't remove
  377. // some other entry by mistake ( likewise for `CMAKE_STAGING_PREFIX` )
  378. entry_to_remove install_entry("INSTALL", this->Makefile);
  379. entry_to_remove staging_entry("STAGING", this->Makefile);
  380. if (remove_install_prefix && install_prefix_in_list &&
  381. (install_entry.valid() || staging_entry.valid())) {
  382. cmValue prefix_paths =
  383. this->Makefile->GetDefinition("CMAKE_SYSTEM_PREFIX_PATH");
  384. // remove entries from CMAKE_SYSTEM_PREFIX_PATH
  385. cmList expanded{ *prefix_paths };
  386. install_entry.remove_self(expanded);
  387. staging_entry.remove_self(expanded);
  388. for (std::string& p : expanded) {
  389. p = cmSystemTools::CollapseFullPath(
  390. p, this->Makefile->GetCurrentSourceDirectory());
  391. }
  392. paths.AddPrefixPaths(expanded);
  393. } else if (add_install_prefix && !install_prefix_in_list) {
  394. paths.AddCMakePrefixPath("CMAKE_INSTALL_PREFIX");
  395. paths.AddCMakePrefixPath("CMAKE_STAGING_PREFIX");
  396. paths.AddCMakePrefixPath("CMAKE_SYSTEM_PREFIX_PATH");
  397. } else {
  398. // Otherwise the current setup of `CMAKE_SYSTEM_PREFIX_PATH` is correct
  399. paths.AddCMakePrefixPath("CMAKE_SYSTEM_PREFIX_PATH");
  400. }
  401. std::string var = cmStrCat("CMAKE_SYSTEM_", this->CMakePathName, "_PATH");
  402. paths.AddCMakePath(var);
  403. if (this->CMakePathName == "PROGRAM") {
  404. paths.AddCMakePath("CMAKE_SYSTEM_APPBUNDLE_PATH");
  405. } else {
  406. paths.AddCMakePath("CMAKE_SYSTEM_FRAMEWORK_PATH");
  407. }
  408. paths.AddSuffixes(this->SearchPathSuffixes);
  409. }
  410. void cmFindBase::FillUserHintsPath()
  411. {
  412. cmSearchPath& paths = this->LabeledPaths[PathLabel::Hints];
  413. for (std::string const& p : this->UserHintsArgs) {
  414. paths.AddUserPath(p);
  415. }
  416. paths.AddSuffixes(this->SearchPathSuffixes);
  417. }
  418. void cmFindBase::FillUserGuessPath()
  419. {
  420. cmSearchPath& paths = this->LabeledPaths[PathLabel::Guess];
  421. for (std::string const& p : this->UserGuessArgs) {
  422. paths.AddUserPath(p);
  423. }
  424. paths.AddSuffixes(this->SearchPathSuffixes);
  425. }
  426. cmFindBase::FindState cmFindBase::GetInitialState()
  427. {
  428. if (cmValue value = this->Makefile->GetDefinition(this->VariableName)) {
  429. cmState* state = this->Makefile->GetState();
  430. cmValue cacheEntry = state->GetCacheEntryValue(this->VariableName);
  431. bool found = !cmIsNOTFOUND(*value);
  432. bool cached = cacheEntry != nullptr;
  433. auto cacheType = cached ? state->GetCacheEntryType(this->VariableName)
  434. : cmStateEnums::UNINITIALIZED;
  435. if (cached && cacheType != cmStateEnums::UNINITIALIZED) {
  436. this->VariableType = cacheType;
  437. if (auto const& hs =
  438. state->GetCacheEntryProperty(this->VariableName, "HELPSTRING")) {
  439. this->VariableDocumentation = *hs;
  440. }
  441. }
  442. if (found) {
  443. // If the user specifies the entry on the command line without a
  444. // type we should add the type and docstring but keep the
  445. // original value. Tell the subclass implementations to do
  446. // this.
  447. if (cached && cacheType == cmStateEnums::UNINITIALIZED) {
  448. this->AlreadyInCacheWithoutMetaInfo = true;
  449. }
  450. return FindState::Found;
  451. }
  452. return FindState::NotFound;
  453. }
  454. return FindState::Undefined;
  455. }
  456. bool cmFindBase::IsFound() const
  457. {
  458. return this->InitialState == FindState::Found;
  459. }
  460. bool cmFindBase::IsDefined() const
  461. {
  462. return this->InitialState != FindState::Undefined;
  463. }
  464. void cmFindBase::NormalizeFindResult()
  465. {
  466. if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0125) ==
  467. cmPolicies::NEW) {
  468. // ensure the path returned by find_* command is absolute
  469. auto const& existingValue =
  470. this->Makefile->GetDefinition(this->VariableName);
  471. std::string value;
  472. if (!existingValue->empty()) {
  473. value =
  474. cmCMakePath(*existingValue, cmCMakePath::auto_format)
  475. .Absolute(cmCMakePath(
  476. this->Makefile->GetCMakeInstance()->GetCMakeWorkingDirectory()))
  477. .Normal()
  478. .GenericString();
  479. if (!cmSystemTools::FileExists(value, false)) {
  480. value = *existingValue;
  481. }
  482. }
  483. if (this->StoreResultInCache) {
  484. // If the user specifies the entry on the command line without a
  485. // type we should add the type and docstring but keep the original
  486. // value.
  487. if (value != *existingValue || this->AlreadyInCacheWithoutMetaInfo) {
  488. this->Makefile->GetCMakeInstance()->AddCacheEntry(
  489. this->VariableName, value, this->VariableDocumentation,
  490. this->VariableType);
  491. if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0126) ==
  492. cmPolicies::NEW) {
  493. if (this->Makefile->IsNormalDefinitionSet(this->VariableName)) {
  494. this->Makefile->AddDefinition(this->VariableName, value);
  495. }
  496. } else {
  497. // if there was a definition then remove it
  498. // This is required to ensure same behavior as
  499. // cmMakefile::AddCacheDefinition.
  500. this->Makefile->RemoveDefinition(this->VariableName);
  501. }
  502. }
  503. } else {
  504. // ensure a normal variable is defined.
  505. this->Makefile->AddDefinition(this->VariableName, value);
  506. }
  507. } else {
  508. // If the user specifies the entry on the command line without a
  509. // type we should add the type and docstring but keep the original
  510. // value.
  511. if (this->StoreResultInCache) {
  512. if (this->AlreadyInCacheWithoutMetaInfo) {
  513. this->Makefile->AddCacheDefinition(this->VariableName, "",
  514. this->VariableDocumentation,
  515. this->VariableType);
  516. if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0126) ==
  517. cmPolicies::NEW &&
  518. this->Makefile->IsNormalDefinitionSet(this->VariableName)) {
  519. this->Makefile->AddDefinition(
  520. this->VariableName,
  521. *this->Makefile->GetCMakeInstance()->GetCacheDefinition(
  522. this->VariableName));
  523. }
  524. }
  525. } else {
  526. // ensure a normal variable is defined.
  527. this->Makefile->AddDefinition(
  528. this->VariableName,
  529. this->Makefile->GetSafeDefinition(this->VariableName));
  530. }
  531. }
  532. }
  533. void cmFindBase::StoreFindResult(std::string const& value)
  534. {
  535. bool force =
  536. this->Makefile->GetPolicyStatus(cmPolicies::CMP0125) == cmPolicies::NEW;
  537. bool updateNormalVariable =
  538. this->Makefile->GetPolicyStatus(cmPolicies::CMP0126) == cmPolicies::NEW;
  539. if (!value.empty()) {
  540. if (this->StoreResultInCache) {
  541. this->Makefile->AddCacheDefinition(this->VariableName, value,
  542. this->VariableDocumentation,
  543. this->VariableType, force);
  544. if (updateNormalVariable &&
  545. this->Makefile->IsNormalDefinitionSet(this->VariableName)) {
  546. this->Makefile->AddDefinition(this->VariableName, value);
  547. }
  548. } else {
  549. this->Makefile->AddDefinition(this->VariableName, value);
  550. }
  551. return;
  552. }
  553. auto notFound = cmStrCat(this->VariableName, "-NOTFOUND");
  554. if (this->StoreResultInCache) {
  555. this->Makefile->AddCacheDefinition(this->VariableName, notFound,
  556. this->VariableDocumentation,
  557. this->VariableType, force);
  558. if (updateNormalVariable &&
  559. this->Makefile->IsNormalDefinitionSet(this->VariableName)) {
  560. this->Makefile->AddDefinition(this->VariableName, notFound);
  561. }
  562. } else {
  563. this->Makefile->AddDefinition(this->VariableName, notFound);
  564. }
  565. if (this->Required) {
  566. this->Makefile->IssueMessage(
  567. MessageType::FATAL_ERROR,
  568. cmStrCat("Could not find ", this->VariableName, " using the following ",
  569. (this->FindCommandName == "find_file" ||
  570. this->FindCommandName == "find_path"
  571. ? "files"
  572. : "names"),
  573. ": ", cmJoin(this->Names, ", ")));
  574. cmSystemTools::SetFatalErrorOccurred();
  575. }
  576. }
  577. cmFindBaseDebugState::cmFindBaseDebugState(cmFindBase const* findBase)
  578. : FindCommand(findBase)
  579. , CommandName(findBase->FindCommandName)
  580. {
  581. }
  582. cmFindBaseDebugState::~cmFindBaseDebugState()
  583. {
  584. bool found = !this->FoundSearchLocation.path.empty();
  585. #ifndef CMAKE_BOOTSTRAP
  586. // Write find event to the configure log if the log exists
  587. if (cmConfigureLog* log =
  588. this->FindCommand->Makefile->GetCMakeInstance()->GetConfigureLog()) {
  589. // Write event if any of:
  590. // - debug mode is enabled
  591. // - the variable was not defined (first run)
  592. // - the variable found state does not match the new found state (state
  593. // transition)
  594. if (this->FindCommand->DebugMode || !this->FindCommand->IsDefined() ||
  595. this->FindCommand->IsFound() != found) {
  596. this->WriteFindEvent(*log, *this->FindCommand->Makefile);
  597. }
  598. }
  599. #endif
  600. if (!this->FindCommand->DebugMode) {
  601. return;
  602. }
  603. // clang-format off
  604. auto buffer =
  605. cmStrCat(
  606. this->CommandName, " called with the following settings:"
  607. "\n VAR: ", this->FindCommand->VariableName,
  608. "\n NAMES: ", cmWrap('"', this->FindCommand->Names, '"', "\n "),
  609. "\n Documentation: ", this->FindCommand->VariableDocumentation,
  610. "\n Framework"
  611. "\n Only Search Frameworks: ", this->FindCommand->SearchFrameworkOnly,
  612. "\n Search Frameworks Last: ", this->FindCommand->SearchFrameworkLast,
  613. "\n Search Frameworks First: ", this->FindCommand->SearchFrameworkFirst,
  614. "\n AppBundle"
  615. "\n Only Search AppBundle: ", this->FindCommand->SearchAppBundleOnly,
  616. "\n Search AppBundle Last: ", this->FindCommand->SearchAppBundleLast,
  617. "\n Search AppBundle First: ", this->FindCommand->SearchAppBundleFirst,
  618. "\n"
  619. );
  620. // clang-format on
  621. if (this->FindCommand->NoDefaultPath) {
  622. buffer += " NO_DEFAULT_PATH Enabled\n";
  623. } else {
  624. // clang-format off
  625. buffer += cmStrCat(
  626. " CMAKE_FIND_USE_CMAKE_PATH: ", !this->FindCommand->NoCMakePath,
  627. "\n CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH: ", !this->FindCommand->NoCMakeEnvironmentPath,
  628. "\n CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH: ", !this->FindCommand->NoSystemEnvironmentPath,
  629. "\n CMAKE_FIND_USE_CMAKE_SYSTEM_PATH: ", !this->FindCommand->NoCMakeSystemPath,
  630. "\n CMAKE_FIND_USE_INSTALL_PREFIX: ", !this->FindCommand->NoCMakeInstallPath,
  631. "\n"
  632. );
  633. // clang-format on
  634. }
  635. buffer +=
  636. cmStrCat(this->CommandName, " considered the following locations:\n");
  637. for (auto const& state : this->FailedSearchLocations) {
  638. std::string path = cmStrCat(" ", state.path);
  639. if (!state.regexName.empty()) {
  640. path = cmStrCat(path, '/', state.regexName);
  641. }
  642. buffer += cmStrCat(path, '\n');
  643. }
  644. if (found) {
  645. buffer += cmStrCat("The item was found at\n ",
  646. this->FoundSearchLocation.path, '\n');
  647. } else {
  648. buffer += "The item was not found.\n";
  649. }
  650. this->FindCommand->DebugMessage(buffer);
  651. }
  652. void cmFindBaseDebugState::FoundAt(std::string const& path,
  653. std::string regexName)
  654. {
  655. if (this->TrackSearchProgress()) {
  656. this->FoundSearchLocation = DebugLibState{ std::move(regexName), path };
  657. }
  658. }
  659. void cmFindBaseDebugState::FailedAt(std::string const& path,
  660. std::string regexName)
  661. {
  662. if (this->TrackSearchProgress()) {
  663. this->FailedSearchLocations.emplace_back(std::move(regexName), path);
  664. }
  665. }
  666. #ifndef CMAKE_BOOTSTRAP
  667. void cmFindBaseDebugState::WriteFindEvent(cmConfigureLog& log,
  668. cmMakefile const& mf) const
  669. {
  670. log.BeginEvent("find-v1", mf);
  671. // Mode is the Command name without the "find_" prefix
  672. log.WriteValue("mode"_s, this->CommandName.substr(5));
  673. log.WriteValue("variable"_s, this->FindCommand->VariableName);
  674. log.WriteValue("description"_s, this->FindCommand->VariableDocumentation);
  675. // Yes, this needs to return a `std::string`. If it returns a `const char*`,
  676. // the `WriteValue` method prefers the `bool` overload. There's no overload
  677. // for a `cm::string_view` because the underlying JSON library doesn't
  678. // support `string_view` arguments itself.
  679. auto search_opt_to_str = [](bool first, bool last,
  680. bool only) -> std::string {
  681. return first ? "FIRST" : (last ? "LAST" : (only ? "ONLY" : "NEVER"));
  682. };
  683. log.BeginObject("settings"_s);
  684. log.WriteValue("SearchFramework"_s,
  685. search_opt_to_str(this->FindCommand->SearchFrameworkFirst,
  686. this->FindCommand->SearchFrameworkLast,
  687. this->FindCommand->SearchFrameworkOnly));
  688. log.WriteValue("SearchAppBundle"_s,
  689. search_opt_to_str(this->FindCommand->SearchAppBundleFirst,
  690. this->FindCommand->SearchAppBundleLast,
  691. this->FindCommand->SearchAppBundleOnly));
  692. log.WriteValue("CMAKE_FIND_USE_CMAKE_PATH"_s,
  693. !this->FindCommand->NoCMakePath);
  694. log.WriteValue("CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH"_s,
  695. !this->FindCommand->NoCMakeEnvironmentPath);
  696. log.WriteValue("CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH"_s,
  697. !this->FindCommand->NoSystemEnvironmentPath);
  698. log.WriteValue("CMAKE_FIND_USE_CMAKE_SYSTEM_PATH"_s,
  699. !this->FindCommand->NoCMakeSystemPath);
  700. log.WriteValue("CMAKE_FIND_USE_INSTALL_PREFIX"_s,
  701. !this->FindCommand->NoCMakeInstallPath);
  702. log.EndObject();
  703. log.WriteValue("names"_s, this->FindCommand->Names);
  704. std::vector<std::string> directories;
  705. directories.reserve(this->FailedSearchLocations.size());
  706. for (auto const& location : this->FailedSearchLocations) {
  707. directories.push_back(location.path);
  708. }
  709. log.WriteValue("candidate_directories"_s, this->FindCommand->SearchPaths);
  710. log.WriteValue("searched_directories"_s, directories);
  711. if (!this->FoundSearchLocation.path.empty()) {
  712. log.WriteValue("found"_s, this->FoundSearchLocation.path);
  713. } else {
  714. log.WriteValue("found"_s, false);
  715. }
  716. log.EndEvent();
  717. }
  718. #endif
  719. bool cmFindBaseDebugState::TrackSearchProgress() const
  720. {
  721. // Track search progress if debugging or logging the configure.
  722. return this->FindCommand->DebugMode
  723. #ifndef CMAKE_BOOTSTRAP
  724. || this->FindCommand->Makefile->GetCMakeInstance()->GetConfigureLog()
  725. #endif
  726. ;
  727. }