cmFindPackageCommand.cxx 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764
  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 "cmFindPackageCommand.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <cstdio>
  7. #include <deque>
  8. #include <functional>
  9. #include <iterator>
  10. #include <sstream>
  11. #include <utility>
  12. #include <cm/memory>
  13. #include <cm/optional>
  14. #include <cmext/string_view>
  15. #include "cmsys/Directory.hxx"
  16. #include "cmsys/FStream.hxx"
  17. #include "cmsys/Glob.hxx"
  18. #include "cmsys/RegularExpression.hxx"
  19. #include "cmsys/String.h"
  20. #include "cmAlgorithms.h"
  21. #include "cmDependencyProvider.h"
  22. #include "cmListFileCache.h"
  23. #include "cmMakefile.h"
  24. #include "cmMessageType.h"
  25. #include "cmPolicies.h"
  26. #include "cmRange.h"
  27. #include "cmSearchPath.h"
  28. #include "cmState.h"
  29. #include "cmStateTypes.h"
  30. #include "cmStringAlgorithms.h"
  31. #include "cmSystemTools.h"
  32. #include "cmValue.h"
  33. #include "cmVersion.h"
  34. #include "cmWindowsRegistry.h"
  35. #if defined(__HAIKU__)
  36. # include <FindDirectory.h>
  37. # include <StorageDefs.h>
  38. #endif
  39. #if defined(_WIN32) && !defined(__CYGWIN__)
  40. # include <windows.h>
  41. // http://msdn.microsoft.com/en-us/library/aa384253%28v=vs.85%29.aspx
  42. # if !defined(KEY_WOW64_32KEY)
  43. # define KEY_WOW64_32KEY 0x0200
  44. # endif
  45. # if !defined(KEY_WOW64_64KEY)
  46. # define KEY_WOW64_64KEY 0x0100
  47. # endif
  48. #endif
  49. class cmExecutionStatus;
  50. namespace {
  51. template <template <typename> class Op>
  52. struct StrverscmpOp
  53. {
  54. bool operator()(const std::string& lhs, const std::string& rhs) const
  55. {
  56. return Op<int>()(cmSystemTools::strverscmp(lhs, rhs), 0);
  57. }
  58. };
  59. std::size_t collectPathsForDebug(std::string& buffer,
  60. cmSearchPath const& searchPath,
  61. std::size_t const startIndex = 0)
  62. {
  63. const auto& paths = searchPath.GetPaths();
  64. if (paths.empty()) {
  65. buffer += " none\n";
  66. return 0;
  67. }
  68. for (auto i = startIndex; i < paths.size(); i++) {
  69. buffer += " " + paths[i].Path + "\n";
  70. }
  71. return paths.size();
  72. }
  73. #if !(defined(_WIN32) && !defined(__CYGWIN__))
  74. class cmFindPackageCommandHoldFile
  75. {
  76. const char* File;
  77. public:
  78. cmFindPackageCommandHoldFile(const char* const f)
  79. : File(f)
  80. {
  81. }
  82. ~cmFindPackageCommandHoldFile()
  83. {
  84. if (this->File) {
  85. cmSystemTools::RemoveFile(this->File);
  86. }
  87. }
  88. cmFindPackageCommandHoldFile(const cmFindPackageCommandHoldFile&) = delete;
  89. cmFindPackageCommandHoldFile& operator=(
  90. const cmFindPackageCommandHoldFile&) = delete;
  91. void Release() { this->File = nullptr; }
  92. };
  93. #endif
  94. // Parse the version number and store the results that were
  95. // successfully parsed.
  96. int parseVersion(const std::string& version, unsigned int& major,
  97. unsigned int& minor, unsigned int& patch, unsigned int& tweak)
  98. {
  99. return std::sscanf(version.c_str(), "%u.%u.%u.%u", &major, &minor, &patch,
  100. &tweak);
  101. }
  102. } // anonymous namespace
  103. cmFindPackageCommand::PathLabel
  104. cmFindPackageCommand::PathLabel::PackageRedirect("PACKAGE_REDIRECT");
  105. cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::UserRegistry(
  106. "PACKAGE_REGISTRY");
  107. cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::Builds(
  108. "BUILDS");
  109. cmFindPackageCommand::PathLabel
  110. cmFindPackageCommand::PathLabel::SystemRegistry("SYSTEM_PACKAGE_REGISTRY");
  111. const cm::string_view cmFindPackageCommand::VERSION_ENDPOINT_INCLUDED(
  112. "INCLUDE");
  113. const cm::string_view cmFindPackageCommand::VERSION_ENDPOINT_EXCLUDED(
  114. "EXCLUDE");
  115. void cmFindPackageCommand::Sort(std::vector<std::string>::iterator begin,
  116. std::vector<std::string>::iterator end,
  117. SortOrderType const order,
  118. SortDirectionType const dir)
  119. {
  120. if (order == Name_order) {
  121. if (dir == Dec) {
  122. std::sort(begin, end, std::greater<std::string>());
  123. } else {
  124. std::sort(begin, end);
  125. }
  126. } else if (order == Natural) {
  127. // natural order uses letters and numbers (contiguous numbers digit are
  128. // compared such that e.g. 000 00 < 01 < 010 < 09 < 0 < 1 < 9 < 10
  129. if (dir == Dec) {
  130. std::sort(begin, end, StrverscmpOp<std::greater>());
  131. } else {
  132. std::sort(begin, end, StrverscmpOp<std::less>());
  133. }
  134. }
  135. // else do not sort
  136. }
  137. cmFindPackageCommand::cmFindPackageCommand(cmExecutionStatus& status)
  138. : cmFindCommon(status)
  139. , VersionRangeMin(VERSION_ENDPOINT_INCLUDED)
  140. , VersionRangeMax(VERSION_ENDPOINT_INCLUDED)
  141. {
  142. this->CMakePathName = "PACKAGE";
  143. this->DebugMode = false;
  144. this->AppendSearchPathGroups();
  145. this->DeprecatedFindModules["Qt"] = cmPolicies::CMP0084;
  146. }
  147. void cmFindPackageCommand::AppendSearchPathGroups()
  148. {
  149. // Update the All group with new paths. Note that package redirection must
  150. // take precedence over everything else, so it has to be first in the array.
  151. std::vector<cmFindCommon::PathLabel>* const labels =
  152. &this->PathGroupLabelMap[PathGroup::All];
  153. labels->insert(labels->begin(), PathLabel::PackageRedirect);
  154. labels->insert(
  155. std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
  156. PathLabel::UserRegistry);
  157. labels->insert(
  158. std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
  159. PathLabel::Builds);
  160. labels->insert(std::find(labels->begin(), labels->end(), PathLabel::Guess),
  161. PathLabel::SystemRegistry);
  162. // Create the new path objects
  163. this->LabeledPaths.insert(
  164. std::make_pair(PathLabel::PackageRedirect, cmSearchPath(this)));
  165. this->LabeledPaths.insert(
  166. std::make_pair(PathLabel::UserRegistry, cmSearchPath(this)));
  167. this->LabeledPaths.insert(
  168. std::make_pair(PathLabel::Builds, cmSearchPath(this)));
  169. this->LabeledPaths.insert(
  170. std::make_pair(PathLabel::SystemRegistry, cmSearchPath(this)));
  171. }
  172. bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args)
  173. {
  174. if (args.empty()) {
  175. this->SetError("called with incorrect number of arguments");
  176. return false;
  177. }
  178. // Lookup required version of CMake.
  179. if (cmValue const rv =
  180. this->Makefile->GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION")) {
  181. unsigned int v[3] = { 0, 0, 0 };
  182. std::sscanf(rv->c_str(), "%u.%u.%u", &v[0], &v[1], &v[2]);
  183. this->RequiredCMakeVersion = CMake_VERSION_ENCODE(v[0], v[1], v[2]);
  184. }
  185. // Lookup target architecture, if any.
  186. if (cmValue const arch =
  187. this->Makefile->GetDefinition("CMAKE_LIBRARY_ARCHITECTURE")) {
  188. this->LibraryArchitecture = *arch;
  189. }
  190. // Lookup whether lib32 paths should be used.
  191. if (this->Makefile->PlatformIs32Bit() &&
  192. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  193. "FIND_LIBRARY_USE_LIB32_PATHS")) {
  194. this->UseLib32Paths = true;
  195. }
  196. // Lookup whether lib64 paths should be used.
  197. if (this->Makefile->PlatformIs64Bit() &&
  198. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  199. "FIND_LIBRARY_USE_LIB64_PATHS")) {
  200. this->UseLib64Paths = true;
  201. }
  202. // Lookup whether libx32 paths should be used.
  203. if (this->Makefile->PlatformIsx32() &&
  204. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  205. "FIND_LIBRARY_USE_LIBX32_PATHS")) {
  206. this->UseLibx32Paths = true;
  207. }
  208. // Check if User Package Registry should be disabled
  209. // The `CMAKE_FIND_USE_PACKAGE_REGISTRY` has
  210. // priority over the deprecated CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY
  211. if (cmValue const def =
  212. this->Makefile->GetDefinition("CMAKE_FIND_USE_PACKAGE_REGISTRY")) {
  213. this->NoUserRegistry = !cmIsOn(*def);
  214. } else if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY")) {
  215. this->NoUserRegistry = true;
  216. }
  217. // Check if System Package Registry should be disabled
  218. // The `CMAKE_FIND_USE_SYSTEM_PACKAGE_REGISTRY` has
  219. // priority over the deprecated CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY
  220. if (cmValue const def = this->Makefile->GetDefinition(
  221. "CMAKE_FIND_USE_SYSTEM_PACKAGE_REGISTRY")) {
  222. this->NoSystemRegistry = !cmIsOn(*def);
  223. } else if (this->Makefile->IsOn(
  224. "CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY")) {
  225. this->NoSystemRegistry = true;
  226. }
  227. // Check whether we should resolve symlinks when finding packages
  228. if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS")) {
  229. this->UseRealPath = true;
  230. }
  231. // Check if Sorting should be enabled
  232. if (cmValue const so =
  233. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_ORDER")) {
  234. if (*so == "NAME") {
  235. this->SortOrder = Name_order;
  236. } else if (*so == "NATURAL") {
  237. this->SortOrder = Natural;
  238. } else {
  239. this->SortOrder = None;
  240. }
  241. }
  242. if (cmValue const sd =
  243. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_DIRECTION")) {
  244. this->SortDirection = (*sd == "ASC") ? Asc : Dec;
  245. }
  246. // Find what search path locations have been enabled/disable
  247. this->SelectDefaultSearchModes();
  248. // Find the current root path mode.
  249. this->SelectDefaultRootPathMode();
  250. // Find the current bundle/framework search policy.
  251. this->SelectDefaultMacMode();
  252. // Record options.
  253. this->Name = args[0];
  254. std::string components;
  255. const char* components_sep = "";
  256. std::set<std::string> requiredComponents;
  257. std::set<std::string> optionalComponents;
  258. std::vector<std::pair<std::string, const char*>> componentVarDefs;
  259. bool bypassProvider = false;
  260. // Always search directly in a generated path.
  261. this->SearchPathSuffixes.emplace_back();
  262. // Process debug mode
  263. cmMakefile::DebugFindPkgRAII debugFindPkgRAII(this->Makefile, this->Name);
  264. this->DebugMode = this->ComputeIfDebugModeWanted();
  265. // Parse the arguments.
  266. enum Doing
  267. {
  268. DoingNone,
  269. DoingComponents,
  270. DoingOptionalComponents,
  271. DoingNames,
  272. DoingPaths,
  273. DoingPathSuffixes,
  274. DoingConfigs,
  275. DoingHints
  276. };
  277. Doing doing = DoingNone;
  278. cmsys::RegularExpression versionRegex(
  279. R"V(^([0-9]+(\.[0-9]+)*)(\.\.\.(<?)([0-9]+(\.[0-9]+)*))?$)V");
  280. bool haveVersion = false;
  281. std::vector<std::size_t> configArgs;
  282. std::vector<std::size_t> moduleArgs;
  283. for (std::size_t i = 1u; i < args.size(); ++i) {
  284. if (args[i] == "QUIET") {
  285. this->Quiet = true;
  286. doing = DoingNone;
  287. } else if (args[i] == "BYPASS_PROVIDER") {
  288. bypassProvider = true;
  289. doing = DoingNone;
  290. } else if (args[i] == "EXACT") {
  291. this->VersionExact = true;
  292. doing = DoingNone;
  293. } else if (args[i] == "GLOBAL") {
  294. this->GlobalScope = true;
  295. doing = DoingNone;
  296. } else if (args[i] == "MODULE") {
  297. moduleArgs.push_back(i);
  298. doing = DoingNone;
  299. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  300. // NOLINTNEXTLINE(bugprone-branch-clone)
  301. } else if (args[i] == "CONFIG") {
  302. configArgs.push_back(i);
  303. doing = DoingNone;
  304. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  305. // NOLINTNEXTLINE(bugprone-branch-clone)
  306. } else if (args[i] == "NO_MODULE") {
  307. configArgs.push_back(i);
  308. doing = DoingNone;
  309. } else if (args[i] == "REQUIRED") {
  310. this->Required = true;
  311. doing = DoingComponents;
  312. } else if (args[i] == "COMPONENTS") {
  313. doing = DoingComponents;
  314. } else if (args[i] == "OPTIONAL_COMPONENTS") {
  315. doing = DoingOptionalComponents;
  316. } else if (args[i] == "NAMES") {
  317. configArgs.push_back(i);
  318. doing = DoingNames;
  319. } else if (args[i] == "PATHS") {
  320. configArgs.push_back(i);
  321. doing = DoingPaths;
  322. } else if (args[i] == "HINTS") {
  323. configArgs.push_back(i);
  324. doing = DoingHints;
  325. } else if (args[i] == "PATH_SUFFIXES") {
  326. configArgs.push_back(i);
  327. doing = DoingPathSuffixes;
  328. } else if (args[i] == "CONFIGS") {
  329. configArgs.push_back(i);
  330. doing = DoingConfigs;
  331. } else if (args[i] == "NO_POLICY_SCOPE") {
  332. this->PolicyScope = false;
  333. doing = DoingNone;
  334. } else if (args[i] == "NO_CMAKE_PACKAGE_REGISTRY") {
  335. this->NoUserRegistry = true;
  336. configArgs.push_back(i);
  337. doing = DoingNone;
  338. } else if (args[i] == "NO_CMAKE_SYSTEM_PACKAGE_REGISTRY") {
  339. this->NoSystemRegistry = true;
  340. configArgs.push_back(i);
  341. doing = DoingNone;
  342. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  343. // NOLINTNEXTLINE(bugprone-branch-clone)
  344. } else if (args[i] == "NO_CMAKE_BUILDS_PATH") {
  345. // Ignore legacy option.
  346. configArgs.push_back(i);
  347. doing = DoingNone;
  348. } else if (args[i] == "REGISTRY_VIEW") {
  349. if (++i == args.size()) {
  350. this->SetError("missing required argument for \"REGISTRY_VIEW\"");
  351. return false;
  352. }
  353. auto view = cmWindowsRegistry::ToView(args[i]);
  354. if (view) {
  355. this->RegistryView = *view;
  356. this->RegistryViewDefined = true;
  357. } else {
  358. this->SetError(
  359. cmStrCat("given invalid value for \"REGISTRY_VIEW\": ", args[i]));
  360. return false;
  361. }
  362. } else if (this->CheckCommonArgument(args[i])) {
  363. configArgs.push_back(i);
  364. doing = DoingNone;
  365. } else if ((doing == DoingComponents) ||
  366. (doing == DoingOptionalComponents)) {
  367. // Set a variable telling the find script whether this component
  368. // is required.
  369. const char* isRequired = "1";
  370. if (doing == DoingOptionalComponents) {
  371. isRequired = "0";
  372. optionalComponents.insert(args[i]);
  373. } else {
  374. requiredComponents.insert(args[i]);
  375. }
  376. componentVarDefs.emplace_back(this->Name + "_FIND_REQUIRED_" + args[i],
  377. isRequired);
  378. // Append to the list of required components.
  379. components += components_sep;
  380. components += args[i];
  381. components_sep = ";";
  382. } else if (doing == DoingNames) {
  383. this->Names.push_back(args[i]);
  384. } else if (doing == DoingPaths) {
  385. this->UserGuessArgs.push_back(args[i]);
  386. } else if (doing == DoingHints) {
  387. this->UserHintsArgs.push_back(args[i]);
  388. } else if (doing == DoingPathSuffixes) {
  389. this->AddPathSuffix(args[i]);
  390. } else if (doing == DoingConfigs) {
  391. if (args[i].find_first_of(":/\\") != std::string::npos ||
  392. cmSystemTools::GetFilenameLastExtension(args[i]) != ".cmake") {
  393. this->SetError(cmStrCat(
  394. "given CONFIGS option followed by invalid file name \"", args[i],
  395. "\". The names given must be file names without "
  396. "a path and with a \".cmake\" extension."));
  397. return false;
  398. }
  399. this->Configs.push_back(args[i]);
  400. } else if (!haveVersion && versionRegex.find(args[i])) {
  401. haveVersion = true;
  402. this->VersionComplete = args[i];
  403. } else {
  404. this->SetError(
  405. cmStrCat("called with invalid argument \"", args[i], "\""));
  406. return false;
  407. }
  408. }
  409. if (!this->GlobalScope) {
  410. cmValue value(
  411. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_TARGETS_GLOBAL"));
  412. this->GlobalScope = value.IsOn();
  413. }
  414. std::vector<std::string> doubledComponents;
  415. std::set_intersection(requiredComponents.begin(), requiredComponents.end(),
  416. optionalComponents.begin(), optionalComponents.end(),
  417. std::back_inserter(doubledComponents));
  418. if (!doubledComponents.empty()) {
  419. this->SetError(
  420. cmStrCat("called with components that are both required and "
  421. "optional:\n",
  422. cmWrap(" ", doubledComponents, "", "\n"), "\n"));
  423. return false;
  424. }
  425. // Check and eliminate search modes not allowed by the args provided
  426. this->UseFindModules = configArgs.empty();
  427. this->UseConfigFiles = moduleArgs.empty();
  428. if (!this->UseFindModules && !this->UseConfigFiles) {
  429. std::ostringstream e;
  430. e << "given options exclusive to Module mode:\n";
  431. for (auto si : moduleArgs) {
  432. e << " " << args[si] << "\n";
  433. }
  434. e << "and options exclusive to Config mode:\n";
  435. for (auto si : configArgs) {
  436. e << " " << args[si] << "\n";
  437. }
  438. e << "The options are incompatible.";
  439. this->SetError(e.str());
  440. return false;
  441. }
  442. // Ignore EXACT with no version.
  443. if (this->VersionComplete.empty() && this->VersionExact) {
  444. this->VersionExact = false;
  445. this->Makefile->IssueMessage(
  446. MessageType::AUTHOR_WARNING,
  447. "Ignoring EXACT since no version is requested.");
  448. }
  449. if (this->VersionComplete.empty() || components.empty()) {
  450. // Check whether we are recursing inside "Find<name>.cmake" within
  451. // another find_package(<name>) call.
  452. std::string const mod = cmStrCat(this->Name, "_FIND_MODULE");
  453. if (this->Makefile->IsOn(mod)) {
  454. if (this->VersionComplete.empty()) {
  455. // Get version information from the outer call if necessary.
  456. // Requested version string.
  457. std::string const ver = cmStrCat(this->Name, "_FIND_VERSION_COMPLETE");
  458. this->VersionComplete = this->Makefile->GetSafeDefinition(ver);
  459. // Whether an exact version is required.
  460. std::string const exact = cmStrCat(this->Name, "_FIND_VERSION_EXACT");
  461. this->VersionExact = this->Makefile->IsOn(exact);
  462. }
  463. if (components.empty()) {
  464. std::string const components_var = this->Name + "_FIND_COMPONENTS";
  465. components = this->Makefile->GetSafeDefinition(components_var);
  466. }
  467. }
  468. }
  469. // fill various parts of version specification
  470. if (!this->VersionComplete.empty()) {
  471. if (!versionRegex.find(this->VersionComplete)) {
  472. this->SetError("called with invalid version specification.");
  473. return false;
  474. }
  475. this->Version = versionRegex.match(1);
  476. this->VersionMax = versionRegex.match(5);
  477. if (versionRegex.match(4) == "<"_s) {
  478. this->VersionRangeMax = VERSION_ENDPOINT_EXCLUDED;
  479. }
  480. if (!this->VersionMax.empty()) {
  481. this->VersionRange = this->VersionComplete;
  482. }
  483. }
  484. if (!this->VersionRange.empty()) {
  485. // version range must not be empty
  486. if ((this->VersionRangeMax == VERSION_ENDPOINT_INCLUDED &&
  487. cmSystemTools::VersionCompareGreater(this->Version,
  488. this->VersionMax)) ||
  489. (this->VersionRangeMax == VERSION_ENDPOINT_EXCLUDED &&
  490. cmSystemTools::VersionCompareGreaterEq(this->Version,
  491. this->VersionMax))) {
  492. this->SetError("specified version range is empty.");
  493. return false;
  494. }
  495. }
  496. if (this->VersionExact && !this->VersionRange.empty()) {
  497. this->SetError("EXACT cannot be specified with a version range.");
  498. return false;
  499. }
  500. if (!this->Version.empty()) {
  501. this->VersionCount =
  502. parseVersion(this->Version, this->VersionMajor, this->VersionMinor,
  503. this->VersionPatch, this->VersionTweak);
  504. }
  505. if (!this->VersionMax.empty()) {
  506. this->VersionMaxCount = parseVersion(
  507. this->VersionMax, this->VersionMaxMajor, this->VersionMaxMinor,
  508. this->VersionMaxPatch, this->VersionMaxTweak);
  509. }
  510. const std::string makePackageRequiredVar =
  511. cmStrCat("CMAKE_REQUIRE_FIND_PACKAGE_", this->Name);
  512. const bool makePackageRequiredSet =
  513. this->Makefile->IsOn(makePackageRequiredVar);
  514. if (makePackageRequiredSet) {
  515. if (this->Required) {
  516. this->Makefile->IssueMessage(
  517. MessageType::WARNING,
  518. cmStrCat("for module ", this->Name,
  519. " already called with REQUIRED, thus ",
  520. makePackageRequiredVar, " has no effect."));
  521. } else {
  522. this->Required = true;
  523. }
  524. }
  525. std::string const disableFindPackageVar =
  526. cmStrCat("CMAKE_DISABLE_FIND_PACKAGE_", this->Name);
  527. if (this->Makefile->IsOn(disableFindPackageVar)) {
  528. if (this->Required) {
  529. this->SetError(
  530. cmStrCat("for module ", this->Name,
  531. (makePackageRequiredSet
  532. ? " was made REQUIRED with " + makePackageRequiredVar
  533. : " called with REQUIRED, "),
  534. " but ", disableFindPackageVar,
  535. " is enabled. A REQUIRED package cannot be disabled."));
  536. return false;
  537. }
  538. return true;
  539. }
  540. // Now choose what method(s) we will use to satisfy the request. Note that
  541. // we still want all the above checking of arguments, etc. regardless of the
  542. // method used. This will ensure ill-formed arguments are caught earlier,
  543. // before things like dependency providers need to deal with them.
  544. // A dependency provider (if set) gets first look before other methods.
  545. // We do this before modifying the package root path stack because a
  546. // provider might use methods that ignore that.
  547. cmState* const state = this->Makefile->GetState();
  548. cmState::Command const providerCommand = state->GetDependencyProviderCommand(
  549. cmDependencyProvider::Method::FindPackage);
  550. if (bypassProvider) {
  551. if (this->DebugMode && providerCommand) {
  552. this->DebugMessage(
  553. "BYPASS_PROVIDER given, skipping dependency provider");
  554. }
  555. } else if (providerCommand) {
  556. if (this->DebugMode) {
  557. this->DebugMessage(cmStrCat("Trying dependency provider command: ",
  558. state->GetDependencyProvider()->GetCommand(),
  559. "()"));
  560. }
  561. std::vector<cmListFileArgument> listFileArgs(args.size() + 1);
  562. listFileArgs[0] =
  563. cmListFileArgument("FIND_PACKAGE", cmListFileArgument::Unquoted, 0);
  564. std::transform(args.begin(), args.end(), listFileArgs.begin() + 1,
  565. [](const std::string& arg) {
  566. return cmListFileArgument(arg,
  567. cmListFileArgument::Bracket, 0);
  568. });
  569. if (!providerCommand(listFileArgs, this->Status)) {
  570. return false;
  571. }
  572. if (this->Makefile->IsOn(cmStrCat(this->Name, "_FOUND"))) {
  573. if (this->DebugMode) {
  574. this->DebugMessage("Package was found by the dependency provider");
  575. }
  576. this->AppendSuccessInformation();
  577. return true;
  578. }
  579. }
  580. {
  581. // Allocate a PACKAGE_ROOT_PATH for the current find_package call.
  582. this->Makefile->FindPackageRootPathStack.emplace_back();
  583. std::vector<std::string>& rootPaths =
  584. this->Makefile->FindPackageRootPathStack.back();
  585. // Add root paths from <PackageName>_ROOT CMake and environment variables,
  586. // subject to CMP0074.
  587. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0074)) {
  588. case cmPolicies::WARN:
  589. this->Makefile->MaybeWarnCMP0074(this->Name);
  590. CM_FALLTHROUGH;
  591. case cmPolicies::OLD:
  592. // OLD behavior is to ignore the <pkg>_ROOT variables.
  593. break;
  594. case cmPolicies::REQUIRED_IF_USED:
  595. case cmPolicies::REQUIRED_ALWAYS:
  596. this->Makefile->IssueMessage(
  597. MessageType::FATAL_ERROR,
  598. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0074));
  599. break;
  600. case cmPolicies::NEW: {
  601. // NEW behavior is to honor the <pkg>_ROOT variables.
  602. std::string const rootVar = this->Name + "_ROOT";
  603. this->Makefile->GetDefExpandList(rootVar, rootPaths, false);
  604. cmSystemTools::GetPath(rootPaths, rootVar.c_str());
  605. } break;
  606. }
  607. }
  608. this->SetModuleVariables(components, componentVarDefs);
  609. // See if we have been told to delegate to FetchContent or some other
  610. // redirected config package first. We have to check all names that
  611. // find_package() may look for, but only need to invoke the override for the
  612. // first one that matches.
  613. auto overrideNames = this->Names;
  614. if (overrideNames.empty()) {
  615. overrideNames.push_back(this->Name);
  616. }
  617. bool forceConfigMode = false;
  618. const auto redirectsDir =
  619. this->Makefile->GetSafeDefinition("CMAKE_FIND_PACKAGE_REDIRECTS_DIR");
  620. for (const auto& overrideName : overrideNames) {
  621. const auto nameLower = cmSystemTools::LowerCase(overrideName);
  622. const auto delegatePropName =
  623. cmStrCat("_FetchContent_", nameLower, "_override_find_package");
  624. const cmValue delegateToFetchContentProp =
  625. this->Makefile->GetState()->GetGlobalProperty(delegatePropName);
  626. if (delegateToFetchContentProp.IsOn()) {
  627. // When this property is set, the FetchContent module has already been
  628. // included at least once, so we know the FetchContent_MakeAvailable()
  629. // command will be defined. Any future find_package() calls after this
  630. // one for this package will by-pass this once-only delegation.
  631. // The following call will typically create a <name>-config.cmake file
  632. // in the redirectsDir, which we still want to process like any other
  633. // config file to ensure we follow normal find_package() processing.
  634. cmListFileFunction func(
  635. "FetchContent_MakeAvailable", 0, 0,
  636. { cmListFileArgument(overrideName, cmListFileArgument::Unquoted, 0) });
  637. if (!this->Makefile->ExecuteCommand(func, this->Status)) {
  638. return false;
  639. }
  640. }
  641. if (cmSystemTools::FileExists(
  642. cmStrCat(redirectsDir, '/', nameLower, "-config.cmake")) ||
  643. cmSystemTools::FileExists(
  644. cmStrCat(redirectsDir, '/', overrideName, "Config.cmake"))) {
  645. // Force the use of this redirected config package file, regardless of
  646. // the type of find_package() call. Files in the redirectsDir must always
  647. // take priority over everything else.
  648. forceConfigMode = true;
  649. this->UseConfigFiles = true;
  650. this->UseFindModules = false;
  651. this->Names.clear();
  652. this->Names.emplace_back(overrideName); // Force finding this one
  653. this->Variable = cmStrCat(this->Name, "_DIR");
  654. this->SetConfigDirCacheVariable(redirectsDir);
  655. break;
  656. }
  657. }
  658. // See if there is a Find<PackageName>.cmake module.
  659. bool loadedPackage = false;
  660. if (forceConfigMode) {
  661. loadedPackage = this->FindPackageUsingConfigMode();
  662. } else if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_PREFER_CONFIG")) {
  663. if (this->UseConfigFiles && this->FindPackageUsingConfigMode()) {
  664. loadedPackage = true;
  665. } else {
  666. if (this->FindPackageUsingModuleMode()) {
  667. loadedPackage = true;
  668. } else {
  669. // The package was not loaded. Report errors.
  670. if (this->HandlePackageMode(HandlePackageModeType::Module)) {
  671. loadedPackage = true;
  672. }
  673. }
  674. }
  675. } else {
  676. if (this->UseFindModules && this->FindPackageUsingModuleMode()) {
  677. loadedPackage = true;
  678. } else {
  679. // Handle CMAKE_FIND_PACKAGE_WARN_NO_MODULE (warn when CONFIG mode is
  680. // implicitly assumed)
  681. if (this->UseFindModules && this->UseConfigFiles &&
  682. this->Makefile->IsOn("CMAKE_FIND_PACKAGE_WARN_NO_MODULE")) {
  683. std::ostringstream aw;
  684. if (this->RequiredCMakeVersion >= CMake_VERSION_ENCODE(2, 8, 8)) {
  685. aw << "find_package called without either MODULE or CONFIG option "
  686. "and "
  687. "no Find"
  688. << this->Name
  689. << ".cmake module is in CMAKE_MODULE_PATH. "
  690. "Add MODULE to exclusively request Module mode and fail if "
  691. "Find"
  692. << this->Name
  693. << ".cmake is missing. "
  694. "Add CONFIG to exclusively request Config mode and search for "
  695. "a "
  696. "package configuration file provided by "
  697. << this->Name << " (" << this->Name << "Config.cmake or "
  698. << cmSystemTools::LowerCase(this->Name) << "-config.cmake). ";
  699. } else {
  700. aw << "find_package called without NO_MODULE option and no "
  701. "Find"
  702. << this->Name
  703. << ".cmake module is in CMAKE_MODULE_PATH. "
  704. "Add NO_MODULE to exclusively request Config mode and search "
  705. "for a "
  706. "package configuration file provided by "
  707. << this->Name << " (" << this->Name << "Config.cmake or "
  708. << cmSystemTools::LowerCase(this->Name)
  709. << "-config.cmake). Otherwise make Find" << this->Name
  710. << ".cmake available in CMAKE_MODULE_PATH.";
  711. }
  712. aw << "\n"
  713. "(Variable CMAKE_FIND_PACKAGE_WARN_NO_MODULE enabled this "
  714. "warning.)";
  715. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
  716. }
  717. if (this->FindPackageUsingConfigMode()) {
  718. loadedPackage = true;
  719. }
  720. }
  721. }
  722. this->AppendSuccessInformation();
  723. // Restore original state of "_FIND_" variables set in SetModuleVariables()
  724. this->RestoreFindDefinitions();
  725. // Pop the package stack
  726. this->Makefile->FindPackageRootPathStack.pop_back();
  727. if (!this->DebugBuffer.empty()) {
  728. this->DebugMessage(this->DebugBuffer);
  729. }
  730. return loadedPackage;
  731. }
  732. bool cmFindPackageCommand::FindPackageUsingModuleMode()
  733. {
  734. bool foundModule = false;
  735. if (!this->FindModule(foundModule)) {
  736. return false;
  737. }
  738. return foundModule;
  739. }
  740. bool cmFindPackageCommand::FindPackageUsingConfigMode()
  741. {
  742. this->Variable = cmStrCat(this->Name, "_DIR");
  743. // Add the default name.
  744. if (this->Names.empty()) {
  745. this->Names.push_back(this->Name);
  746. }
  747. // Add the default configs.
  748. if (this->Configs.empty()) {
  749. for (std::string const& n : this->Names) {
  750. std::string config = cmStrCat(n, "Config.cmake");
  751. this->Configs.push_back(config);
  752. config = cmStrCat(cmSystemTools::LowerCase(n), "-config.cmake");
  753. this->Configs.push_back(std::move(config));
  754. }
  755. }
  756. // get igonored paths from vars and reroot them.
  757. std::vector<std::string> ignored;
  758. this->GetIgnoredPaths(ignored);
  759. this->RerootPaths(ignored);
  760. // Construct a set of ignored paths
  761. this->IgnoredPaths.clear();
  762. this->IgnoredPaths.insert(ignored.begin(), ignored.end());
  763. // get igonored prefix paths from vars and reroot them.
  764. std::vector<std::string> ignoredPrefixes;
  765. this->GetIgnoredPrefixPaths(ignoredPrefixes);
  766. this->RerootPaths(ignoredPrefixes);
  767. // Construct a set of ignored prefix paths
  768. this->IgnoredPrefixPaths.clear();
  769. this->IgnoredPrefixPaths.insert(ignoredPrefixes.begin(),
  770. ignoredPrefixes.end());
  771. // Find and load the package.
  772. return this->HandlePackageMode(HandlePackageModeType::Config);
  773. }
  774. void cmFindPackageCommand::SetVersionVariables(
  775. const std::function<void(const std::string&, cm::string_view)>&
  776. addDefinition,
  777. const std::string& prefix, const std::string& version,
  778. const unsigned int count, const unsigned int major, const unsigned int minor,
  779. const unsigned int patch, const unsigned int tweak)
  780. {
  781. addDefinition(prefix, version);
  782. char buf[64];
  783. snprintf(buf, sizeof(buf), "%u", major);
  784. addDefinition(prefix + "_MAJOR", buf);
  785. snprintf(buf, sizeof(buf), "%u", minor);
  786. addDefinition(prefix + "_MINOR", buf);
  787. snprintf(buf, sizeof(buf), "%u", patch);
  788. addDefinition(prefix + "_PATCH", buf);
  789. snprintf(buf, sizeof(buf), "%u", tweak);
  790. addDefinition(prefix + "_TWEAK", buf);
  791. snprintf(buf, sizeof(buf), "%u", count);
  792. addDefinition(prefix + "_COUNT", buf);
  793. }
  794. void cmFindPackageCommand::SetModuleVariables(
  795. const std::string& components,
  796. const std::vector<std::pair<std::string, const char*>>& componentVarDefs)
  797. {
  798. this->AddFindDefinition("CMAKE_FIND_PACKAGE_NAME", this->Name);
  799. // Store the list of components and associated variable definitions
  800. std::string components_var = this->Name + "_FIND_COMPONENTS";
  801. this->AddFindDefinition(components_var, components);
  802. for (const auto& varDef : componentVarDefs) {
  803. this->AddFindDefinition(varDef.first, varDef.second);
  804. }
  805. if (this->Quiet) {
  806. // Tell the module that is about to be read that it should find
  807. // quietly.
  808. std::string quietly = cmStrCat(this->Name, "_FIND_QUIETLY");
  809. this->AddFindDefinition(quietly, "1"_s);
  810. }
  811. if (this->Required) {
  812. // Tell the module that is about to be read that it should report
  813. // a fatal error if the package is not found.
  814. std::string req = cmStrCat(this->Name, "_FIND_REQUIRED");
  815. this->AddFindDefinition(req, "1"_s);
  816. }
  817. if (!this->VersionComplete.empty()) {
  818. std::string req = cmStrCat(this->Name, "_FIND_VERSION_COMPLETE");
  819. this->AddFindDefinition(req, this->VersionComplete);
  820. }
  821. // Tell the module that is about to be read what version of the
  822. // package has been requested.
  823. auto addDefinition = [this](const std::string& variable,
  824. cm::string_view value) {
  825. this->AddFindDefinition(variable, value);
  826. };
  827. if (!this->Version.empty()) {
  828. auto prefix = cmStrCat(this->Name, "_FIND_VERSION"_s);
  829. this->SetVersionVariables(addDefinition, prefix, this->Version,
  830. this->VersionCount, this->VersionMajor,
  831. this->VersionMinor, this->VersionPatch,
  832. this->VersionTweak);
  833. // Tell the module whether an exact version has been requested.
  834. auto exact = cmStrCat(this->Name, "_FIND_VERSION_EXACT");
  835. this->AddFindDefinition(exact, this->VersionExact ? "1"_s : "0"_s);
  836. }
  837. if (!this->VersionRange.empty()) {
  838. auto prefix = cmStrCat(this->Name, "_FIND_VERSION_MIN"_s);
  839. this->SetVersionVariables(addDefinition, prefix, this->Version,
  840. this->VersionCount, this->VersionMajor,
  841. this->VersionMinor, this->VersionPatch,
  842. this->VersionTweak);
  843. prefix = cmStrCat(this->Name, "_FIND_VERSION_MAX"_s);
  844. this->SetVersionVariables(addDefinition, prefix, this->VersionMax,
  845. this->VersionMaxCount, this->VersionMaxMajor,
  846. this->VersionMaxMinor, this->VersionMaxPatch,
  847. this->VersionMaxTweak);
  848. auto id = cmStrCat(this->Name, "_FIND_VERSION_RANGE");
  849. this->AddFindDefinition(id, this->VersionRange);
  850. id = cmStrCat(this->Name, "_FIND_VERSION_RANGE_MIN");
  851. this->AddFindDefinition(id, this->VersionRangeMin);
  852. id = cmStrCat(this->Name, "_FIND_VERSION_RANGE_MAX");
  853. this->AddFindDefinition(id, this->VersionRangeMax);
  854. }
  855. if (this->RegistryViewDefined) {
  856. this->AddFindDefinition(cmStrCat(this->Name, "_FIND_REGISTRY_VIEW"),
  857. cmWindowsRegistry::FromView(this->RegistryView));
  858. }
  859. }
  860. void cmFindPackageCommand::AddFindDefinition(const std::string& var,
  861. const cm::string_view value)
  862. {
  863. if (cmValue old = this->Makefile->GetDefinition(var)) {
  864. this->OriginalDefs[var].exists = true;
  865. this->OriginalDefs[var].value = *old;
  866. } else {
  867. this->OriginalDefs[var].exists = false;
  868. }
  869. this->Makefile->AddDefinition(var, value);
  870. }
  871. void cmFindPackageCommand::RestoreFindDefinitions()
  872. {
  873. for (auto const& i : this->OriginalDefs) {
  874. OriginalDef const& od = i.second;
  875. if (od.exists) {
  876. this->Makefile->AddDefinition(i.first, od.value);
  877. } else {
  878. this->Makefile->RemoveDefinition(i.first);
  879. }
  880. }
  881. }
  882. bool cmFindPackageCommand::FindModule(bool& found)
  883. {
  884. std::string moduleFileName = cmStrCat("Find", this->Name, ".cmake");
  885. bool system = false;
  886. std::string debugBuffer = cmStrCat(
  887. "find_package considered the following paths for ", moduleFileName, ":\n");
  888. std::string mfile = this->Makefile->GetModulesFile(
  889. moduleFileName, system, this->DebugMode, debugBuffer);
  890. if (this->DebugMode) {
  891. if (mfile.empty()) {
  892. debugBuffer = cmStrCat(debugBuffer, "The file was not found.\n");
  893. } else {
  894. debugBuffer =
  895. cmStrCat(debugBuffer, "The file was found at\n ", mfile, "\n");
  896. }
  897. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  898. }
  899. if (!mfile.empty()) {
  900. if (system) {
  901. auto const it = this->DeprecatedFindModules.find(this->Name);
  902. if (it != this->DeprecatedFindModules.end()) {
  903. cmPolicies::PolicyStatus status =
  904. this->Makefile->GetPolicyStatus(it->second);
  905. switch (status) {
  906. case cmPolicies::WARN: {
  907. this->Makefile->IssueMessage(
  908. MessageType::AUTHOR_WARNING,
  909. cmStrCat(cmPolicies::GetPolicyWarning(it->second), "\n"));
  910. CM_FALLTHROUGH;
  911. }
  912. case cmPolicies::OLD:
  913. break;
  914. case cmPolicies::REQUIRED_IF_USED:
  915. case cmPolicies::REQUIRED_ALWAYS:
  916. case cmPolicies::NEW:
  917. return true;
  918. }
  919. }
  920. }
  921. // Load the module we found, and set "<name>_FIND_MODULE" to true
  922. // while inside it.
  923. found = true;
  924. std::string const var = cmStrCat(this->Name, "_FIND_MODULE");
  925. this->Makefile->AddDefinition(var, "1");
  926. bool result = this->ReadListFile(mfile, DoPolicyScope);
  927. this->Makefile->RemoveDefinition(var);
  928. if (this->DebugMode) {
  929. std::string const foundVar = cmStrCat(this->Name, "_FOUND");
  930. if (this->Makefile->IsDefinitionSet(foundVar) &&
  931. !this->Makefile->IsOn(foundVar)) {
  932. this->DebugBuffer = cmStrCat(
  933. this->DebugBuffer, "The module is considered not found due to ",
  934. foundVar, " being FALSE.");
  935. }
  936. }
  937. return result;
  938. }
  939. return true;
  940. }
  941. bool cmFindPackageCommand::HandlePackageMode(
  942. const HandlePackageModeType handlePackageModeType)
  943. {
  944. this->ConsideredConfigs.clear();
  945. // Try to find the config file.
  946. cmValue def = this->Makefile->GetDefinition(this->Variable);
  947. // Try to load the config file if the directory is known
  948. bool fileFound = false;
  949. if (this->UseConfigFiles) {
  950. if (!cmIsOff(def)) {
  951. // Get the directory from the variable value.
  952. std::string dir = *def;
  953. cmSystemTools::ConvertToUnixSlashes(dir);
  954. // Treat relative paths with respect to the current source dir.
  955. if (!cmSystemTools::FileIsFullPath(dir)) {
  956. dir = "/" + dir;
  957. dir = this->Makefile->GetCurrentSourceDirectory() + dir;
  958. }
  959. // The file location was cached. Look for the correct file.
  960. std::string file;
  961. if (this->FindConfigFile(dir, file)) {
  962. this->FileFound = file;
  963. fileFound = true;
  964. }
  965. def = this->Makefile->GetDefinition(this->Variable);
  966. }
  967. // Search for the config file if it is not already found.
  968. if (cmIsOff(def) || !fileFound) {
  969. fileFound = this->FindConfig();
  970. }
  971. // Sanity check.
  972. if (fileFound && this->FileFound.empty()) {
  973. this->Makefile->IssueMessage(
  974. MessageType::INTERNAL_ERROR,
  975. "fileFound is true but FileFound is empty!");
  976. fileFound = false;
  977. }
  978. }
  979. std::string const foundVar = cmStrCat(this->Name, "_FOUND");
  980. std::string const notFoundMessageVar =
  981. cmStrCat(this->Name, "_NOT_FOUND_MESSAGE");
  982. std::string notFoundMessage;
  983. // If the directory for the config file was found, try to read the file.
  984. bool result = true;
  985. bool found = false;
  986. bool configFileSetFOUNDFalse = false;
  987. if (fileFound) {
  988. if (this->Makefile->IsDefinitionSet(foundVar) &&
  989. !this->Makefile->IsOn(foundVar)) {
  990. // by removing Foo_FOUND here if it is FALSE, we don't really change
  991. // the situation for the Config file which is about to be included,
  992. // but we make it possible to detect later on whether the Config file
  993. // has set Foo_FOUND to FALSE itself:
  994. this->Makefile->RemoveDefinition(foundVar);
  995. }
  996. this->Makefile->RemoveDefinition(notFoundMessageVar);
  997. // Set the version variables before loading the config file.
  998. // It may override them.
  999. this->StoreVersionFound();
  1000. // Parse the configuration file.
  1001. if (this->ReadListFile(this->FileFound, DoPolicyScope)) {
  1002. // The package has been found.
  1003. found = true;
  1004. // Check whether the Config file has set Foo_FOUND to FALSE:
  1005. if (this->Makefile->IsDefinitionSet(foundVar) &&
  1006. !this->Makefile->IsOn(foundVar)) {
  1007. // we get here if the Config file has set Foo_FOUND actively to FALSE
  1008. found = false;
  1009. configFileSetFOUNDFalse = true;
  1010. notFoundMessage =
  1011. this->Makefile->GetSafeDefinition(notFoundMessageVar);
  1012. }
  1013. } else {
  1014. // The configuration file is invalid.
  1015. result = false;
  1016. }
  1017. }
  1018. if (this->UseFindModules && !found &&
  1019. handlePackageModeType == HandlePackageModeType::Config &&
  1020. this->Makefile->IsOn("CMAKE_FIND_PACKAGE_PREFER_CONFIG")) {
  1021. // Config mode failed. Allow Module case.
  1022. result = false;
  1023. }
  1024. // package not found
  1025. if (result && !found) {
  1026. // warn if package required or neither quiet nor in config mode
  1027. if (this->Required ||
  1028. !(this->Quiet ||
  1029. (this->UseConfigFiles && !this->UseFindModules &&
  1030. this->ConsideredConfigs.empty()))) {
  1031. // The variable is not set.
  1032. std::ostringstream e;
  1033. std::ostringstream aw;
  1034. if (configFileSetFOUNDFalse) {
  1035. /* clang-format off */
  1036. e << "Found package configuration file:\n"
  1037. " " << this->FileFound << "\n"
  1038. "but it set " << foundVar << " to FALSE so package \"" <<
  1039. this->Name << "\" is considered to be NOT FOUND.";
  1040. /* clang-format on */
  1041. if (!notFoundMessage.empty()) {
  1042. e << " Reason given by package: \n" << notFoundMessage << "\n";
  1043. }
  1044. }
  1045. // If there are files in ConsideredConfigs, it means that FooConfig.cmake
  1046. // have been found, but they didn't have appropriate versions.
  1047. else if (!this->ConsideredConfigs.empty()) {
  1048. auto duplicate_end = cmRemoveDuplicates(this->ConsideredConfigs);
  1049. e << "Could not find a configuration file for package \"" << this->Name
  1050. << "\" that "
  1051. << (this->VersionExact ? "exactly matches" : "is compatible with")
  1052. << " requested version "
  1053. << (this->VersionRange.empty() ? "" : "range ") << "\""
  1054. << this->VersionComplete
  1055. << "\".\n"
  1056. "The following configuration files were considered but not "
  1057. "accepted:\n";
  1058. for (ConfigFileInfo const& info :
  1059. cmMakeRange(this->ConsideredConfigs.cbegin(), duplicate_end)) {
  1060. e << " " << info.filename << ", version: " << info.version << "\n";
  1061. }
  1062. } else {
  1063. std::string requestedVersionString;
  1064. if (!this->VersionComplete.empty()) {
  1065. requestedVersionString =
  1066. cmStrCat(" (requested version ", this->VersionComplete, ')');
  1067. }
  1068. if (this->UseConfigFiles) {
  1069. if (this->UseFindModules) {
  1070. e << "By not providing \"Find" << this->Name
  1071. << ".cmake\" in "
  1072. "CMAKE_MODULE_PATH this project has asked CMake to find a "
  1073. "package configuration file provided by \""
  1074. << this->Name
  1075. << "\", "
  1076. "but CMake did not find one.\n";
  1077. }
  1078. if (this->Configs.size() == 1) {
  1079. e << "Could not find a package configuration file named \""
  1080. << this->Configs[0] << "\" provided by package \"" << this->Name
  1081. << "\"" << requestedVersionString << ".\n";
  1082. } else {
  1083. e << "Could not find a package configuration file provided by \""
  1084. << this->Name << "\"" << requestedVersionString
  1085. << " with any of the following names:\n"
  1086. << cmWrap(" ", this->Configs, "", "\n") << "\n";
  1087. }
  1088. e << "Add the installation prefix of \"" << this->Name
  1089. << "\" to "
  1090. "CMAKE_PREFIX_PATH or set \""
  1091. << this->Variable
  1092. << "\" to a "
  1093. "directory containing one of the above files. "
  1094. "If \""
  1095. << this->Name
  1096. << "\" provides a separate development "
  1097. "package or SDK, be sure it has been installed.";
  1098. } else // if(!this->UseFindModules && !this->UseConfigFiles)
  1099. {
  1100. e << "No \"Find" << this->Name
  1101. << ".cmake\" found in "
  1102. "CMAKE_MODULE_PATH.";
  1103. aw
  1104. << "Find" << this->Name
  1105. << ".cmake must either be part of this "
  1106. "project itself, in this case adjust CMAKE_MODULE_PATH so that "
  1107. "it points to the correct location inside its source tree.\n"
  1108. "Or it must be installed by a package which has already been "
  1109. "found via find_package(). In this case make sure that "
  1110. "package has indeed been found and adjust CMAKE_MODULE_PATH to "
  1111. "contain the location where that package has installed "
  1112. "Find"
  1113. << this->Name
  1114. << ".cmake. This must be a location "
  1115. "provided by that package. This error in general means that "
  1116. "the buildsystem of this project is relying on a Find-module "
  1117. "without ensuring that it is actually available.\n";
  1118. }
  1119. }
  1120. this->Makefile->IssueMessage(this->Required ? MessageType::FATAL_ERROR
  1121. : MessageType::WARNING,
  1122. e.str());
  1123. if (this->Required) {
  1124. cmSystemTools::SetFatalErrorOccurred();
  1125. }
  1126. if (!aw.str().empty()) {
  1127. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
  1128. }
  1129. }
  1130. // output result if in config mode but not in quiet mode
  1131. else if (!this->Quiet) {
  1132. this->Makefile->DisplayStatus(cmStrCat("Could NOT find ", this->Name,
  1133. " (missing: ", this->Name,
  1134. "_DIR)"),
  1135. -1);
  1136. }
  1137. }
  1138. // Set a variable marking whether the package was found.
  1139. this->Makefile->AddDefinition(foundVar, found ? "1" : "0");
  1140. // Set a variable naming the configuration file that was found.
  1141. std::string const fileVar = cmStrCat(this->Name, "_CONFIG");
  1142. if (found) {
  1143. this->Makefile->AddDefinition(fileVar, this->FileFound);
  1144. } else {
  1145. this->Makefile->RemoveDefinition(fileVar);
  1146. }
  1147. std::string const consideredConfigsVar =
  1148. cmStrCat(this->Name, "_CONSIDERED_CONFIGS");
  1149. std::string const consideredVersionsVar =
  1150. cmStrCat(this->Name, "_CONSIDERED_VERSIONS");
  1151. std::string consideredConfigFiles;
  1152. std::string consideredVersions;
  1153. const char* sep = "";
  1154. for (ConfigFileInfo const& i : this->ConsideredConfigs) {
  1155. consideredConfigFiles += sep;
  1156. consideredVersions += sep;
  1157. consideredConfigFiles += i.filename;
  1158. consideredVersions += i.version;
  1159. sep = ";";
  1160. }
  1161. this->Makefile->AddDefinition(consideredConfigsVar, consideredConfigFiles);
  1162. this->Makefile->AddDefinition(consideredVersionsVar, consideredVersions);
  1163. return result;
  1164. }
  1165. bool cmFindPackageCommand::FindConfig()
  1166. {
  1167. // Compute the set of search prefixes.
  1168. this->ComputePrefixes();
  1169. // Look for the project's configuration file.
  1170. bool found = false;
  1171. if (this->DebugMode) {
  1172. this->DebugBuffer = cmStrCat(this->DebugBuffer,
  1173. "find_package considered the following "
  1174. "locations for ",
  1175. this->Name, "'s Config module:\n");
  1176. }
  1177. // Search for frameworks.
  1178. if (!found && (this->SearchFrameworkFirst || this->SearchFrameworkOnly)) {
  1179. found = this->FindFrameworkConfig();
  1180. }
  1181. // Search for apps.
  1182. if (!found && (this->SearchAppBundleFirst || this->SearchAppBundleOnly)) {
  1183. found = this->FindAppBundleConfig();
  1184. }
  1185. // Search prefixes.
  1186. if (!found && !(this->SearchFrameworkOnly || this->SearchAppBundleOnly)) {
  1187. found = this->FindPrefixedConfig();
  1188. }
  1189. // Search for frameworks.
  1190. if (!found && this->SearchFrameworkLast) {
  1191. found = this->FindFrameworkConfig();
  1192. }
  1193. // Search for apps.
  1194. if (!found && this->SearchAppBundleLast) {
  1195. found = this->FindAppBundleConfig();
  1196. }
  1197. if (this->DebugMode) {
  1198. if (found) {
  1199. this->DebugBuffer = cmStrCat(
  1200. this->DebugBuffer, "The file was found at\n ", this->FileFound, "\n");
  1201. } else {
  1202. this->DebugBuffer =
  1203. cmStrCat(this->DebugBuffer, "The file was not found.\n");
  1204. }
  1205. }
  1206. // Store the entry in the cache so it can be set by the user.
  1207. std::string init;
  1208. if (found) {
  1209. init = cmSystemTools::GetFilenamePath(this->FileFound);
  1210. } else {
  1211. init = this->Variable + "-NOTFOUND";
  1212. }
  1213. // We force the value since we do not get here if it was already set.
  1214. this->SetConfigDirCacheVariable(init);
  1215. return found;
  1216. }
  1217. void cmFindPackageCommand::SetConfigDirCacheVariable(const std::string& value)
  1218. {
  1219. std::string const help =
  1220. cmStrCat("The directory containing a CMake configuration file for ",
  1221. this->Name, '.');
  1222. this->Makefile->AddCacheDefinition(this->Variable, value, help.c_str(),
  1223. cmStateEnums::PATH, true);
  1224. if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0126) ==
  1225. cmPolicies::NEW &&
  1226. this->Makefile->IsNormalDefinitionSet(this->Variable)) {
  1227. this->Makefile->AddDefinition(this->Variable, value);
  1228. }
  1229. }
  1230. bool cmFindPackageCommand::FindPrefixedConfig()
  1231. {
  1232. std::vector<std::string> const& prefixes = this->SearchPaths;
  1233. return std::any_of(
  1234. prefixes.begin(), prefixes.end(),
  1235. [this](std::string const& p) -> bool { return this->SearchPrefix(p); });
  1236. }
  1237. bool cmFindPackageCommand::FindFrameworkConfig()
  1238. {
  1239. std::vector<std::string> const& prefixes = this->SearchPaths;
  1240. return std::any_of(prefixes.begin(), prefixes.end(),
  1241. [this](std::string const& p) -> bool {
  1242. return this->SearchFrameworkPrefix(p);
  1243. });
  1244. }
  1245. bool cmFindPackageCommand::FindAppBundleConfig()
  1246. {
  1247. std::vector<std::string> const& prefixes = this->SearchPaths;
  1248. return std::any_of(prefixes.begin(), prefixes.end(),
  1249. [this](std::string const& p) -> bool {
  1250. return this->SearchAppBundlePrefix(p);
  1251. });
  1252. }
  1253. bool cmFindPackageCommand::ReadListFile(const std::string& f,
  1254. const PolicyScopeRule psr)
  1255. {
  1256. const bool noPolicyScope = !this->PolicyScope || psr == NoPolicyScope;
  1257. using ITScope = cmMakefile::ImportedTargetScope;
  1258. ITScope scope = this->GlobalScope ? ITScope::Global : ITScope::Local;
  1259. cmMakefile::SetGlobalTargetImportScope globScope(this->Makefile, scope);
  1260. if (this->Makefile->ReadDependentFile(f, noPolicyScope)) {
  1261. return true;
  1262. }
  1263. std::string const e = cmStrCat("Error reading CMake code from \"", f, "\".");
  1264. this->SetError(e);
  1265. return false;
  1266. }
  1267. void cmFindPackageCommand::AppendToFoundProperty(const bool found)
  1268. {
  1269. std::vector<std::string> foundContents;
  1270. cmValue foundProp =
  1271. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_FOUND");
  1272. if (cmNonempty(foundProp)) {
  1273. cmExpandList(*foundProp, foundContents, false);
  1274. auto nameIt =
  1275. std::find(foundContents.begin(), foundContents.end(), this->Name);
  1276. if (nameIt != foundContents.end()) {
  1277. foundContents.erase(nameIt);
  1278. }
  1279. }
  1280. std::vector<std::string> notFoundContents;
  1281. cmValue notFoundProp =
  1282. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_NOT_FOUND");
  1283. if (cmNonempty(notFoundProp)) {
  1284. cmExpandList(*notFoundProp, notFoundContents, false);
  1285. auto nameIt =
  1286. std::find(notFoundContents.begin(), notFoundContents.end(), this->Name);
  1287. if (nameIt != notFoundContents.end()) {
  1288. notFoundContents.erase(nameIt);
  1289. }
  1290. }
  1291. if (found) {
  1292. foundContents.push_back(this->Name);
  1293. } else {
  1294. notFoundContents.push_back(this->Name);
  1295. }
  1296. std::string tmp = cmJoin(foundContents, ";");
  1297. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_FOUND", tmp.c_str());
  1298. tmp = cmJoin(notFoundContents, ";");
  1299. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_NOT_FOUND",
  1300. tmp.c_str());
  1301. }
  1302. void cmFindPackageCommand::AppendSuccessInformation()
  1303. {
  1304. {
  1305. std::string const transitivePropName =
  1306. cmStrCat("_CMAKE_", this->Name, "_TRANSITIVE_DEPENDENCY");
  1307. this->Makefile->GetState()->SetGlobalProperty(transitivePropName, "False");
  1308. }
  1309. std::string const found = cmStrCat(this->Name, "_FOUND");
  1310. std::string const upperFound = cmSystemTools::UpperCase(found);
  1311. bool const upperResult = this->Makefile->IsOn(upperFound);
  1312. bool const result = this->Makefile->IsOn(found);
  1313. bool const packageFound = (result || upperResult);
  1314. this->AppendToFoundProperty(packageFound);
  1315. // Record whether the find was quiet or not, so this can be used
  1316. // e.g. in FeatureSummary.cmake
  1317. std::string const quietInfoPropName =
  1318. cmStrCat("_CMAKE_", this->Name, "_QUIET");
  1319. this->Makefile->GetState()->SetGlobalProperty(
  1320. quietInfoPropName, this->Quiet ? "TRUE" : "FALSE");
  1321. // set a global property to record the required version of this package
  1322. std::string const versionInfoPropName =
  1323. cmStrCat("_CMAKE_", this->Name, "_REQUIRED_VERSION");
  1324. std::string versionInfo;
  1325. if (!this->VersionRange.empty()) {
  1326. versionInfo = this->VersionRange;
  1327. } else if (!this->Version.empty()) {
  1328. versionInfo =
  1329. cmStrCat(this->VersionExact ? "==" : ">=", ' ', this->Version);
  1330. }
  1331. this->Makefile->GetState()->SetGlobalProperty(versionInfoPropName,
  1332. versionInfo.c_str());
  1333. if (this->Required) {
  1334. std::string const requiredInfoPropName =
  1335. cmStrCat("_CMAKE_", this->Name, "_TYPE");
  1336. this->Makefile->GetState()->SetGlobalProperty(requiredInfoPropName,
  1337. "REQUIRED");
  1338. }
  1339. }
  1340. void cmFindPackageCommand::ComputePrefixes()
  1341. {
  1342. this->FillPrefixesPackageRedirect();
  1343. if (!this->NoDefaultPath) {
  1344. if (!this->NoPackageRootPath) {
  1345. this->FillPrefixesPackageRoot();
  1346. }
  1347. if (!this->NoCMakePath) {
  1348. this->FillPrefixesCMakeVariable();
  1349. }
  1350. if (!this->NoCMakeEnvironmentPath) {
  1351. this->FillPrefixesCMakeEnvironment();
  1352. }
  1353. }
  1354. this->FillPrefixesUserHints();
  1355. if (!this->NoDefaultPath) {
  1356. if (!this->NoSystemEnvironmentPath) {
  1357. this->FillPrefixesSystemEnvironment();
  1358. }
  1359. if (!this->NoUserRegistry) {
  1360. this->FillPrefixesUserRegistry();
  1361. }
  1362. if (!this->NoCMakeSystemPath) {
  1363. this->FillPrefixesCMakeSystemVariable();
  1364. }
  1365. if (!this->NoSystemRegistry) {
  1366. this->FillPrefixesSystemRegistry();
  1367. }
  1368. }
  1369. this->FillPrefixesUserGuess();
  1370. this->ComputeFinalPaths(IgnorePaths::No);
  1371. }
  1372. void cmFindPackageCommand::FillPrefixesPackageRedirect()
  1373. {
  1374. cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRedirect];
  1375. const auto redirectDir =
  1376. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_REDIRECTS_DIR");
  1377. if (redirectDir && !redirectDir->empty()) {
  1378. paths.AddPath(*redirectDir);
  1379. }
  1380. if (this->DebugMode) {
  1381. std::string debugBuffer =
  1382. "The internally managed CMAKE_FIND_PACKAGE_REDIRECTS_DIR.\n";
  1383. collectPathsForDebug(debugBuffer, paths);
  1384. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1385. }
  1386. }
  1387. void cmFindPackageCommand::FillPrefixesPackageRoot()
  1388. {
  1389. cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRoot];
  1390. // Add the PACKAGE_ROOT_PATH from each enclosing find_package call.
  1391. for (auto pkgPaths = this->Makefile->FindPackageRootPathStack.rbegin();
  1392. pkgPaths != this->Makefile->FindPackageRootPathStack.rend();
  1393. ++pkgPaths) {
  1394. for (std::string const& path : *pkgPaths) {
  1395. paths.AddPath(path);
  1396. }
  1397. }
  1398. if (this->DebugMode) {
  1399. std::string debugBuffer = "<PackageName>_ROOT CMake variable "
  1400. "[CMAKE_FIND_USE_PACKAGE_ROOT_PATH].\n";
  1401. collectPathsForDebug(debugBuffer, paths);
  1402. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1403. }
  1404. }
  1405. void cmFindPackageCommand::FillPrefixesCMakeEnvironment()
  1406. {
  1407. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeEnvironment];
  1408. std::string debugBuffer;
  1409. std::size_t debugOffset = 0;
  1410. // Check the environment variable with the same name as the cache
  1411. // entry.
  1412. paths.AddEnvPath(this->Variable);
  1413. if (this->DebugMode) {
  1414. debugBuffer = cmStrCat("Env variable ", this->Variable,
  1415. " [CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH].\n");
  1416. debugOffset = collectPathsForDebug(debugBuffer, paths);
  1417. }
  1418. // And now the general CMake environment variables
  1419. paths.AddEnvPath("CMAKE_PREFIX_PATH");
  1420. if (this->DebugMode) {
  1421. debugBuffer = cmStrCat(debugBuffer,
  1422. "CMAKE_PREFIX_PATH env variable "
  1423. "[CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH].\n");
  1424. debugOffset = collectPathsForDebug(debugBuffer, paths, debugOffset);
  1425. }
  1426. paths.AddEnvPath("CMAKE_FRAMEWORK_PATH");
  1427. paths.AddEnvPath("CMAKE_APPBUNDLE_PATH");
  1428. if (this->DebugMode) {
  1429. debugBuffer =
  1430. cmStrCat(debugBuffer,
  1431. "CMAKE_FRAMEWORK_PATH and CMAKE_APPBUNDLE_PATH env "
  1432. "variables [CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH].\n");
  1433. collectPathsForDebug(debugBuffer, paths, debugOffset);
  1434. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1435. }
  1436. }
  1437. void cmFindPackageCommand::FillPrefixesCMakeVariable()
  1438. {
  1439. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMake];
  1440. std::string debugBuffer;
  1441. std::size_t debugOffset = 0;
  1442. paths.AddCMakePath("CMAKE_PREFIX_PATH");
  1443. if (this->DebugMode) {
  1444. debugBuffer = "CMAKE_PREFIX_PATH variable [CMAKE_FIND_USE_CMAKE_PATH].\n";
  1445. debugOffset = collectPathsForDebug(debugBuffer, paths);
  1446. }
  1447. paths.AddCMakePath("CMAKE_FRAMEWORK_PATH");
  1448. paths.AddCMakePath("CMAKE_APPBUNDLE_PATH");
  1449. if (this->DebugMode) {
  1450. debugBuffer =
  1451. cmStrCat(debugBuffer,
  1452. "CMAKE_FRAMEWORK_PATH and CMAKE_APPBUNDLE_PATH variables "
  1453. "[CMAKE_FIND_USE_CMAKE_PATH].\n");
  1454. collectPathsForDebug(debugBuffer, paths, debugOffset);
  1455. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1456. }
  1457. }
  1458. void cmFindPackageCommand::FillPrefixesSystemEnvironment()
  1459. {
  1460. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemEnvironment];
  1461. // Use the system search path to generate prefixes.
  1462. // Relative paths are interpreted with respect to the current
  1463. // working directory.
  1464. std::vector<std::string> tmp;
  1465. cmSystemTools::GetPath(tmp);
  1466. for (std::string const& i : tmp) {
  1467. // If the path is a PREFIX/bin case then add its parent instead.
  1468. if ((cmHasLiteralSuffix(i, "/bin")) || (cmHasLiteralSuffix(i, "/sbin"))) {
  1469. paths.AddPath(cmSystemTools::GetFilenamePath(i));
  1470. } else {
  1471. paths.AddPath(i);
  1472. }
  1473. }
  1474. if (this->DebugMode) {
  1475. std::string debugBuffer = "Standard system environment variables "
  1476. "[CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH].\n";
  1477. collectPathsForDebug(debugBuffer, paths);
  1478. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1479. }
  1480. }
  1481. void cmFindPackageCommand::FillPrefixesUserRegistry()
  1482. {
  1483. #if defined(_WIN32) && !defined(__CYGWIN__)
  1484. this->LoadPackageRegistryWinUser();
  1485. #elif defined(__HAIKU__)
  1486. char dir[B_PATH_NAME_LENGTH];
  1487. if (find_directory(B_USER_SETTINGS_DIRECTORY, -1, false, dir, sizeof(dir)) ==
  1488. B_OK) {
  1489. std::string fname = cmStrCat(dir, "/cmake/packages/", Name);
  1490. this->LoadPackageRegistryDir(fname,
  1491. this->LabeledPaths[PathLabel::UserRegistry]);
  1492. }
  1493. #else
  1494. std::string dir;
  1495. if (cmSystemTools::GetEnv("HOME", dir)) {
  1496. dir += "/.cmake/packages/";
  1497. dir += this->Name;
  1498. this->LoadPackageRegistryDir(dir,
  1499. this->LabeledPaths[PathLabel::UserRegistry]);
  1500. }
  1501. #endif
  1502. if (this->DebugMode) {
  1503. std::string debugBuffer =
  1504. "CMake User Package Registry [CMAKE_FIND_USE_PACKAGE_REGISTRY].\n";
  1505. collectPathsForDebug(debugBuffer,
  1506. this->LabeledPaths[PathLabel::UserRegistry]);
  1507. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1508. }
  1509. }
  1510. void cmFindPackageCommand::FillPrefixesSystemRegistry()
  1511. {
  1512. if (this->NoSystemRegistry || this->NoDefaultPath) {
  1513. return;
  1514. }
  1515. #if defined(_WIN32) && !defined(__CYGWIN__)
  1516. this->LoadPackageRegistryWinSystem();
  1517. #endif
  1518. if (this->DebugMode) {
  1519. std::string debugBuffer =
  1520. "CMake System Package Registry "
  1521. "[CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY].\n";
  1522. collectPathsForDebug(debugBuffer,
  1523. this->LabeledPaths[PathLabel::SystemRegistry]);
  1524. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1525. }
  1526. }
  1527. #if defined(_WIN32) && !defined(__CYGWIN__)
  1528. void cmFindPackageCommand::LoadPackageRegistryWinUser()
  1529. {
  1530. // HKEY_CURRENT_USER\\Software shares 32-bit and 64-bit views.
  1531. this->LoadPackageRegistryWin(true, 0,
  1532. this->LabeledPaths[PathLabel::UserRegistry]);
  1533. }
  1534. void cmFindPackageCommand::LoadPackageRegistryWinSystem()
  1535. {
  1536. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemRegistry];
  1537. // HKEY_LOCAL_MACHINE\\SOFTWARE has separate 32-bit and 64-bit views.
  1538. // Prefer the target platform view first.
  1539. if (this->Makefile->PlatformIs64Bit()) {
  1540. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  1541. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  1542. } else {
  1543. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  1544. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  1545. }
  1546. }
  1547. void cmFindPackageCommand::LoadPackageRegistryWin(const bool user,
  1548. const unsigned int view,
  1549. cmSearchPath& outPaths)
  1550. {
  1551. std::wstring key = L"Software\\Kitware\\CMake\\Packages\\";
  1552. key += cmsys::Encoding::ToWide(this->Name);
  1553. std::set<std::wstring> bad;
  1554. HKEY hKey;
  1555. if (RegOpenKeyExW(user ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE, key.c_str(),
  1556. 0, KEY_QUERY_VALUE | view, &hKey) == ERROR_SUCCESS) {
  1557. DWORD valueType = REG_NONE;
  1558. wchar_t name[16383]; // RegEnumValue docs limit name to 32767 _bytes_
  1559. std::vector<wchar_t> data(512);
  1560. bool done = false;
  1561. DWORD index = 0;
  1562. while (!done) {
  1563. DWORD nameSize = static_cast<DWORD>(sizeof(name));
  1564. DWORD dataSize = static_cast<DWORD>(data.size() * sizeof(data[0]));
  1565. switch (RegEnumValueW(hKey, index, name, &nameSize, 0, &valueType,
  1566. (BYTE*)&data[0], &dataSize)) {
  1567. case ERROR_SUCCESS:
  1568. ++index;
  1569. if (valueType == REG_SZ) {
  1570. data[dataSize] = 0;
  1571. if (!this->CheckPackageRegistryEntry(
  1572. cmsys::Encoding::ToNarrow(&data[0]), outPaths)) {
  1573. // The entry is invalid.
  1574. bad.insert(name);
  1575. }
  1576. }
  1577. break;
  1578. case ERROR_MORE_DATA:
  1579. data.resize((dataSize + sizeof(data[0]) - 1) / sizeof(data[0]));
  1580. break;
  1581. case ERROR_NO_MORE_ITEMS:
  1582. default:
  1583. done = true;
  1584. break;
  1585. }
  1586. }
  1587. RegCloseKey(hKey);
  1588. }
  1589. // Remove bad values if possible.
  1590. if (user && !bad.empty() &&
  1591. RegOpenKeyExW(HKEY_CURRENT_USER, key.c_str(), 0, KEY_SET_VALUE | view,
  1592. &hKey) == ERROR_SUCCESS) {
  1593. for (std::wstring const& v : bad) {
  1594. RegDeleteValueW(hKey, v.c_str());
  1595. }
  1596. RegCloseKey(hKey);
  1597. }
  1598. }
  1599. #else
  1600. void cmFindPackageCommand::LoadPackageRegistryDir(std::string const& dir,
  1601. cmSearchPath& outPaths)
  1602. {
  1603. cmsys::Directory files;
  1604. if (!files.Load(dir)) {
  1605. return;
  1606. }
  1607. std::string fname;
  1608. for (unsigned long i = 0; i < files.GetNumberOfFiles(); ++i) {
  1609. fname = cmStrCat(dir, '/', files.GetFile(i));
  1610. if (!cmSystemTools::FileIsDirectory(fname)) {
  1611. // Hold this file hostage until it behaves.
  1612. cmFindPackageCommandHoldFile holdFile(fname.c_str());
  1613. // Load the file.
  1614. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  1615. std::string fentry;
  1616. if (fin && cmSystemTools::GetLineFromStream(fin, fentry) &&
  1617. this->CheckPackageRegistryEntry(fentry, outPaths)) {
  1618. // The file references an existing package, so release it.
  1619. holdFile.Release();
  1620. }
  1621. }
  1622. }
  1623. // TODO: Wipe out the directory if it is empty.
  1624. }
  1625. #endif
  1626. bool cmFindPackageCommand::CheckPackageRegistryEntry(const std::string& fname,
  1627. cmSearchPath& outPaths)
  1628. {
  1629. // Parse the content of one package registry entry.
  1630. if (cmSystemTools::FileIsFullPath(fname)) {
  1631. // The first line in the stream is the full path to a file or
  1632. // directory containing the package.
  1633. if (cmSystemTools::FileExists(fname)) {
  1634. // The path exists. Look for the package here.
  1635. if (!cmSystemTools::FileIsDirectory(fname)) {
  1636. outPaths.AddPath(cmSystemTools::GetFilenamePath(fname));
  1637. } else {
  1638. outPaths.AddPath(fname);
  1639. }
  1640. return true;
  1641. }
  1642. // The path does not exist. Assume the stream content is
  1643. // associated with an old package that no longer exists, and
  1644. // delete it to keep the package registry clean.
  1645. return false;
  1646. }
  1647. // The first line in the stream is not the full path to a file or
  1648. // directory. Assume the stream content was created by a future
  1649. // version of CMake that uses a different format, and leave it.
  1650. return true;
  1651. }
  1652. void cmFindPackageCommand::FillPrefixesCMakeSystemVariable()
  1653. {
  1654. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeSystem];
  1655. const bool install_prefix_in_list =
  1656. !this->Makefile->IsOn("CMAKE_FIND_NO_INSTALL_PREFIX");
  1657. const bool remove_install_prefix = this->NoCMakeInstallPath;
  1658. const bool add_install_prefix = !this->NoCMakeInstallPath &&
  1659. this->Makefile->IsDefinitionSet("CMAKE_FIND_USE_INSTALL_PREFIX");
  1660. // We have 3 possible states for `CMAKE_SYSTEM_PREFIX_PATH` and
  1661. // `CMAKE_INSTALL_PREFIX`.
  1662. // Either we need to remove `CMAKE_INSTALL_PREFIX`, add
  1663. // `CMAKE_INSTALL_PREFIX`, or do nothing.
  1664. //
  1665. // When we need to remove `CMAKE_INSTALL_PREFIX` we remove the Nth occurrence
  1666. // of `CMAKE_INSTALL_PREFIX` from `CMAKE_SYSTEM_PREFIX_PATH`, where `N` is
  1667. // computed by `CMakeSystemSpecificInformation.cmake` while constructing
  1668. // `CMAKE_SYSTEM_PREFIX_PATH`. This ensures that if projects / toolchains
  1669. // have removed `CMAKE_INSTALL_PREFIX` from the list, we don't remove
  1670. // some other entry by mistake
  1671. long install_prefix_count = -1;
  1672. std::string install_path_to_remove;
  1673. if (cmValue to_skip = this->Makefile->GetDefinition(
  1674. "_CMAKE_SYSTEM_PREFIX_PATH_INSTALL_PREFIX_COUNT")) {
  1675. cmStrToLong(to_skip, &install_prefix_count);
  1676. }
  1677. if (cmValue install_value = this->Makefile->GetDefinition(
  1678. "_CMAKE_SYSTEM_PREFIX_PATH_INSTALL_PREFIX_VALUE")) {
  1679. install_path_to_remove = *install_value;
  1680. }
  1681. if (remove_install_prefix && install_prefix_in_list &&
  1682. install_prefix_count > 0 && !install_path_to_remove.empty()) {
  1683. cmValue prefix_paths =
  1684. this->Makefile->GetDefinition("CMAKE_SYSTEM_PREFIX_PATH");
  1685. // remove entry from CMAKE_SYSTEM_PREFIX_PATH
  1686. std::vector<std::string> expanded = cmExpandedList(*prefix_paths);
  1687. long count = 0;
  1688. for (const auto& path : expanded) {
  1689. bool const to_add =
  1690. !(path == install_path_to_remove && ++count == install_prefix_count);
  1691. if (to_add) {
  1692. paths.AddPath(path);
  1693. }
  1694. }
  1695. } else if (add_install_prefix && !install_prefix_in_list) {
  1696. paths.AddCMakePath("CMAKE_INSTALL_PREFIX");
  1697. paths.AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
  1698. } else {
  1699. // Otherwise the current setup of `CMAKE_SYSTEM_PREFIX_PATH` is correct
  1700. paths.AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
  1701. }
  1702. paths.AddCMakePath("CMAKE_SYSTEM_FRAMEWORK_PATH");
  1703. paths.AddCMakePath("CMAKE_SYSTEM_APPBUNDLE_PATH");
  1704. if (this->DebugMode) {
  1705. std::string debugBuffer = "CMake variables defined in the Platform file "
  1706. "[CMAKE_FIND_USE_CMAKE_SYSTEM_PATH].\n";
  1707. collectPathsForDebug(debugBuffer, paths);
  1708. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1709. }
  1710. }
  1711. void cmFindPackageCommand::FillPrefixesUserGuess()
  1712. {
  1713. cmSearchPath& paths = this->LabeledPaths[PathLabel::Guess];
  1714. for (std::string const& p : this->UserGuessArgs) {
  1715. paths.AddUserPath(p);
  1716. }
  1717. if (this->DebugMode) {
  1718. std::string debugBuffer =
  1719. "Paths specified by the find_package PATHS option.\n";
  1720. collectPathsForDebug(debugBuffer, paths);
  1721. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1722. }
  1723. }
  1724. void cmFindPackageCommand::FillPrefixesUserHints()
  1725. {
  1726. cmSearchPath& paths = this->LabeledPaths[PathLabel::Hints];
  1727. for (std::string const& p : this->UserHintsArgs) {
  1728. paths.AddUserPath(p);
  1729. }
  1730. if (this->DebugMode) {
  1731. std::string debugBuffer =
  1732. "Paths specified by the find_package HINTS option.\n";
  1733. collectPathsForDebug(debugBuffer, paths);
  1734. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1735. }
  1736. }
  1737. bool cmFindPackageCommand::SearchDirectory(std::string const& dir)
  1738. {
  1739. assert(!dir.empty() && dir.back() == '/');
  1740. // Check each path suffix on this directory.
  1741. for (std::string const& s : this->SearchPathSuffixes) {
  1742. std::string d = dir;
  1743. if (!s.empty()) {
  1744. d += s;
  1745. d += '/';
  1746. }
  1747. if (this->CheckDirectory(d)) {
  1748. return true;
  1749. }
  1750. }
  1751. return false;
  1752. }
  1753. bool cmFindPackageCommand::CheckDirectory(std::string const& dir)
  1754. {
  1755. assert(!dir.empty() && dir.back() == '/');
  1756. // Look for the file in this directory.
  1757. std::string const d = dir.substr(0, dir.size() - 1);
  1758. if (this->FindConfigFile(d, this->FileFound)) {
  1759. // Remove duplicate slashes.
  1760. cmSystemTools::ConvertToUnixSlashes(this->FileFound);
  1761. return true;
  1762. }
  1763. return false;
  1764. }
  1765. bool cmFindPackageCommand::FindConfigFile(std::string const& dir,
  1766. std::string& file)
  1767. {
  1768. if (this->IgnoredPaths.count(dir)) {
  1769. return false;
  1770. }
  1771. for (std::string const& c : this->Configs) {
  1772. file = cmStrCat(dir, '/', c);
  1773. if (this->DebugMode) {
  1774. this->DebugBuffer = cmStrCat(this->DebugBuffer, " ", file, "\n");
  1775. }
  1776. if (cmSystemTools::FileExists(file, true) && this->CheckVersion(file)) {
  1777. // Allow resolving symlinks when the config file is found through a link
  1778. if (this->UseRealPath) {
  1779. file = cmSystemTools::GetRealPath(file);
  1780. }
  1781. return true;
  1782. }
  1783. }
  1784. return false;
  1785. }
  1786. bool cmFindPackageCommand::CheckVersion(std::string const& config_file)
  1787. {
  1788. bool result = false; // by default, assume the version is not ok.
  1789. bool haveResult = false;
  1790. std::string version = "unknown";
  1791. // Get the filename without the .cmake extension.
  1792. std::string::size_type pos = config_file.rfind('.');
  1793. std::string version_file_base = config_file.substr(0, pos);
  1794. // Look for foo-config-version.cmake
  1795. std::string version_file = cmStrCat(version_file_base, "-version.cmake");
  1796. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  1797. result = this->CheckVersionFile(version_file, version);
  1798. haveResult = true;
  1799. }
  1800. // Look for fooConfigVersion.cmake
  1801. version_file = cmStrCat(version_file_base, "Version.cmake");
  1802. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  1803. result = this->CheckVersionFile(version_file, version);
  1804. haveResult = true;
  1805. }
  1806. // If no version was requested a versionless package is acceptable.
  1807. if (!haveResult && this->Version.empty()) {
  1808. result = true;
  1809. }
  1810. ConfigFileInfo configFileInfo;
  1811. configFileInfo.filename = config_file;
  1812. configFileInfo.version = version;
  1813. this->ConsideredConfigs.push_back(std::move(configFileInfo));
  1814. return result;
  1815. }
  1816. bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file,
  1817. std::string& result_version)
  1818. {
  1819. // The version file will be loaded in an isolated scope.
  1820. cmMakefile::ScopePushPop const varScope(this->Makefile);
  1821. cmMakefile::PolicyPushPop const polScope(this->Makefile);
  1822. static_cast<void>(varScope);
  1823. static_cast<void>(polScope);
  1824. // Clear the output variables.
  1825. this->Makefile->RemoveDefinition("PACKAGE_VERSION");
  1826. this->Makefile->RemoveDefinition("PACKAGE_VERSION_UNSUITABLE");
  1827. this->Makefile->RemoveDefinition("PACKAGE_VERSION_COMPATIBLE");
  1828. this->Makefile->RemoveDefinition("PACKAGE_VERSION_EXACT");
  1829. // Set the input variables.
  1830. this->Makefile->AddDefinition("PACKAGE_FIND_NAME", this->Name);
  1831. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_COMPLETE",
  1832. this->VersionComplete);
  1833. auto addDefinition = [this](const std::string& variable,
  1834. cm::string_view value) {
  1835. this->Makefile->AddDefinition(variable, value);
  1836. };
  1837. this->SetVersionVariables(addDefinition, "PACKAGE_FIND_VERSION",
  1838. this->Version, this->VersionCount,
  1839. this->VersionMajor, this->VersionMinor,
  1840. this->VersionPatch, this->VersionTweak);
  1841. if (!this->VersionRange.empty()) {
  1842. this->SetVersionVariables(addDefinition, "PACKAGE_FIND_VERSION_MIN",
  1843. this->Version, this->VersionCount,
  1844. this->VersionMajor, this->VersionMinor,
  1845. this->VersionPatch, this->VersionTweak);
  1846. this->SetVersionVariables(addDefinition, "PACKAGE_FIND_VERSION_MAX",
  1847. this->VersionMax, this->VersionMaxCount,
  1848. this->VersionMaxMajor, this->VersionMaxMinor,
  1849. this->VersionMaxPatch, this->VersionMaxTweak);
  1850. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_RANGE",
  1851. this->VersionComplete);
  1852. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_RANGE_MIN",
  1853. this->VersionRangeMin);
  1854. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_RANGE_MAX",
  1855. this->VersionRangeMax);
  1856. }
  1857. // Load the version check file. Pass NoPolicyScope because we do
  1858. // our own policy push/pop independent of CMP0011.
  1859. bool suitable = false;
  1860. if (this->ReadListFile(version_file, NoPolicyScope)) {
  1861. // Check the output variables.
  1862. bool okay = this->Makefile->IsOn("PACKAGE_VERSION_EXACT");
  1863. bool const unsuitable = this->Makefile->IsOn("PACKAGE_VERSION_UNSUITABLE");
  1864. if (!okay && !this->VersionExact) {
  1865. okay = this->Makefile->IsOn("PACKAGE_VERSION_COMPATIBLE");
  1866. }
  1867. // The package is suitable if the version is okay and not
  1868. // explicitly unsuitable.
  1869. suitable = !unsuitable && (okay || this->Version.empty());
  1870. if (suitable) {
  1871. // Get the version found.
  1872. this->VersionFound =
  1873. this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  1874. // Try to parse the version number and store the results that were
  1875. // successfully parsed.
  1876. unsigned int parsed_major;
  1877. unsigned int parsed_minor;
  1878. unsigned int parsed_patch;
  1879. unsigned int parsed_tweak;
  1880. this->VersionFoundCount =
  1881. parseVersion(this->VersionFound, parsed_major, parsed_minor,
  1882. parsed_patch, parsed_tweak);
  1883. switch (this->VersionFoundCount) {
  1884. case 4:
  1885. this->VersionFoundTweak = parsed_tweak;
  1886. CM_FALLTHROUGH;
  1887. case 3:
  1888. this->VersionFoundPatch = parsed_patch;
  1889. CM_FALLTHROUGH;
  1890. case 2:
  1891. this->VersionFoundMinor = parsed_minor;
  1892. CM_FALLTHROUGH;
  1893. case 1:
  1894. this->VersionFoundMajor = parsed_major;
  1895. CM_FALLTHROUGH;
  1896. default:
  1897. break;
  1898. }
  1899. }
  1900. }
  1901. result_version = this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  1902. if (result_version.empty()) {
  1903. result_version = "unknown";
  1904. }
  1905. // Succeed if the version is suitable.
  1906. return suitable;
  1907. }
  1908. void cmFindPackageCommand::StoreVersionFound()
  1909. {
  1910. // Store the whole version string.
  1911. std::string const ver = cmStrCat(this->Name, "_VERSION");
  1912. auto addDefinition = [this](const std::string& variable,
  1913. cm::string_view value) {
  1914. this->Makefile->AddDefinition(variable, value);
  1915. };
  1916. this->SetVersionVariables(addDefinition, ver, this->VersionFound,
  1917. this->VersionFoundCount, this->VersionFoundMajor,
  1918. this->VersionFoundMinor, this->VersionFoundPatch,
  1919. this->VersionFoundTweak);
  1920. if (this->VersionFound.empty()) {
  1921. this->Makefile->RemoveDefinition(ver);
  1922. }
  1923. }
  1924. // BEGIN File paths generators
  1925. namespace {
  1926. class cmFileList;
  1927. class cmFileListGeneratorBase
  1928. {
  1929. public:
  1930. virtual ~cmFileListGeneratorBase() = default;
  1931. protected:
  1932. bool Consider(std::string const& fullPath, cmFileList& listing);
  1933. static bool IsIgnoredEntry(const char* fname)
  1934. {
  1935. assert(fname != nullptr);
  1936. assert(fname[0] != 0);
  1937. return fname[0] == '.' &&
  1938. (fname[1] == 0 || (fname[1] == '.' && fname[2] == 0));
  1939. }
  1940. private:
  1941. friend class cmFileList;
  1942. virtual std::unique_ptr<cmFileListGeneratorBase> Clone() const = 0;
  1943. virtual bool Search(std::string const& parent, cmFileList&) = 0;
  1944. bool Search(cmFileList& listing)
  1945. {
  1946. return this->Search(std::string{}, listing);
  1947. }
  1948. cmFileListGeneratorBase* SetNext(cmFileListGeneratorBase const& next)
  1949. {
  1950. this->Next = next.Clone();
  1951. return this->Next.get();
  1952. }
  1953. std::unique_ptr<cmFileListGeneratorBase> Next;
  1954. };
  1955. class cmFileList
  1956. {
  1957. public:
  1958. virtual ~cmFileList() = default;
  1959. cmFileList& operator/(cmFileListGeneratorBase const& rhs)
  1960. {
  1961. if (this->Last) {
  1962. this->Last = this->Last->SetNext(rhs);
  1963. } else {
  1964. this->First = rhs.Clone();
  1965. this->Last = this->First.get();
  1966. }
  1967. return *this;
  1968. }
  1969. bool Search() { return this->First && this->First->Search(*this); }
  1970. private:
  1971. virtual bool Visit(std::string const& fullPath) = 0;
  1972. friend class cmFileListGeneratorBase;
  1973. std::unique_ptr<cmFileListGeneratorBase> First;
  1974. cmFileListGeneratorBase* Last = nullptr;
  1975. };
  1976. bool cmFileListGeneratorBase::Consider(std::string const& fullPath,
  1977. cmFileList& listing)
  1978. {
  1979. if (!fullPath.empty() && !cmSystemTools::FileIsDirectory(fullPath)) {
  1980. return false;
  1981. }
  1982. if (this->Next) {
  1983. return this->Next->Search(fullPath + '/', listing);
  1984. }
  1985. return listing.Visit(fullPath + '/');
  1986. }
  1987. class cmFindPackageFileList : public cmFileList
  1988. {
  1989. public:
  1990. using SearchFn = std::function<bool(const std::string&)>;
  1991. cmFindPackageFileList(const SearchFn search)
  1992. : searchFn(search)
  1993. {
  1994. }
  1995. private:
  1996. bool Visit(std::string const& fullPath) override
  1997. {
  1998. return this->searchFn(fullPath);
  1999. }
  2000. const SearchFn searchFn;
  2001. };
  2002. class cmFileListGeneratorFixed : public cmFileListGeneratorBase
  2003. {
  2004. public:
  2005. cmFileListGeneratorFixed(std::string str)
  2006. : String(std::move(str))
  2007. {
  2008. }
  2009. cmFileListGeneratorFixed(cmFileListGeneratorFixed const& r)
  2010. : String(r.String)
  2011. {
  2012. }
  2013. private:
  2014. std::string String;
  2015. bool Search(std::string const& parent, cmFileList& lister) override
  2016. {
  2017. std::string fullPath = parent + this->String;
  2018. return this->Consider(fullPath, lister);
  2019. }
  2020. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  2021. {
  2022. std::unique_ptr<cmFileListGeneratorBase> g(
  2023. new cmFileListGeneratorFixed(*this));
  2024. return g;
  2025. }
  2026. };
  2027. class cmFileListGeneratorEnumerate : public cmFileListGeneratorBase
  2028. {
  2029. public:
  2030. cmFileListGeneratorEnumerate(std::vector<std::string> const& v)
  2031. : Vector(v)
  2032. {
  2033. }
  2034. cmFileListGeneratorEnumerate(cmFileListGeneratorEnumerate const& r)
  2035. : Vector(r.Vector)
  2036. {
  2037. }
  2038. private:
  2039. std::vector<std::string> const& Vector;
  2040. bool Search(std::string const& parent, cmFileList& lister) override
  2041. {
  2042. return std::any_of(this->Vector.cbegin(), this->Vector.cend(),
  2043. [this, &parent, &lister](std::string const& i) {
  2044. return this->Consider(parent + i, lister);
  2045. });
  2046. }
  2047. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  2048. {
  2049. std::unique_ptr<cmFileListGeneratorBase> g(
  2050. new cmFileListGeneratorEnumerate(*this));
  2051. return g;
  2052. }
  2053. };
  2054. class cmFileListGeneratorProject : public cmFileListGeneratorBase
  2055. {
  2056. public:
  2057. cmFileListGeneratorProject(std::vector<std::string> const& names,
  2058. cmFindPackageCommand::SortOrderType so,
  2059. cmFindPackageCommand::SortDirectionType sd)
  2060. : Names(names)
  2061. {
  2062. this->SetSort(so, sd);
  2063. }
  2064. cmFileListGeneratorProject(cmFileListGeneratorProject const& r)
  2065. : Names(r.Names)
  2066. {
  2067. this->SetSort(r.SortOrder, r.SortDirection);
  2068. }
  2069. void SetSort(cmFindPackageCommand::SortOrderType o,
  2070. cmFindPackageCommand::SortDirectionType d)
  2071. {
  2072. this->SortOrder = o;
  2073. this->SortDirection = d;
  2074. }
  2075. protected:
  2076. // sort parameters
  2077. cmFindPackageCommand::SortOrderType SortOrder;
  2078. cmFindPackageCommand::SortDirectionType SortDirection;
  2079. private:
  2080. std::vector<std::string> const& Names;
  2081. bool Search(std::string const& parent, cmFileList& lister) override
  2082. {
  2083. // Construct a list of matches.
  2084. std::vector<std::string> matches;
  2085. cmsys::Directory d;
  2086. d.Load(parent);
  2087. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  2088. const char* const fname = d.GetFile(i);
  2089. if (this->IsIgnoredEntry(fname)) {
  2090. continue;
  2091. }
  2092. for (std::string const& n : this->Names) {
  2093. if (cmsysString_strncasecmp(fname, n.c_str(), n.length()) == 0) {
  2094. matches.emplace_back(fname);
  2095. }
  2096. }
  2097. }
  2098. // before testing the matches check if there is a specific sorting order to
  2099. // perform
  2100. if (this->SortOrder != cmFindPackageCommand::None) {
  2101. cmFindPackageCommand::Sort(matches.begin(), matches.end(),
  2102. this->SortOrder, this->SortDirection);
  2103. }
  2104. return std::any_of(matches.cbegin(), matches.cend(),
  2105. [this, &parent, &lister](std::string const& i) {
  2106. return this->Consider(parent + i, lister);
  2107. });
  2108. }
  2109. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  2110. {
  2111. std::unique_ptr<cmFileListGeneratorBase> g(
  2112. new cmFileListGeneratorProject(*this));
  2113. return g;
  2114. }
  2115. };
  2116. class cmFileListGeneratorMacProject : public cmFileListGeneratorBase
  2117. {
  2118. public:
  2119. cmFileListGeneratorMacProject(std::vector<std::string> const& names,
  2120. const char* ext)
  2121. : Names(names)
  2122. , Extension(ext)
  2123. {
  2124. }
  2125. cmFileListGeneratorMacProject(cmFileListGeneratorMacProject const& r)
  2126. : Names(r.Names)
  2127. , Extension(r.Extension)
  2128. {
  2129. }
  2130. private:
  2131. std::vector<std::string> const& Names;
  2132. std::string Extension;
  2133. bool Search(std::string const& parent, cmFileList& lister) override
  2134. {
  2135. // Construct a list of matches.
  2136. std::vector<std::string> matches;
  2137. cmsys::Directory d;
  2138. d.Load(parent);
  2139. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  2140. const char* const fname = d.GetFile(i);
  2141. if (this->IsIgnoredEntry(fname)) {
  2142. continue;
  2143. }
  2144. for (std::string name : this->Names) {
  2145. name += this->Extension;
  2146. if (cmsysString_strcasecmp(fname, name.c_str()) == 0) {
  2147. matches.emplace_back(fname);
  2148. }
  2149. }
  2150. }
  2151. return std::any_of(matches.cbegin(), matches.cend(),
  2152. [this, &parent, &lister](std::string const& i) {
  2153. return this->Consider(parent + i, lister);
  2154. });
  2155. }
  2156. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  2157. {
  2158. std::unique_ptr<cmFileListGeneratorBase> g(
  2159. new cmFileListGeneratorMacProject(*this));
  2160. return g;
  2161. }
  2162. };
  2163. class cmFileListGeneratorCaseInsensitive : public cmFileListGeneratorBase
  2164. {
  2165. public:
  2166. cmFileListGeneratorCaseInsensitive(std::string str)
  2167. : String(std::move(str))
  2168. {
  2169. }
  2170. cmFileListGeneratorCaseInsensitive(
  2171. cmFileListGeneratorCaseInsensitive const& r)
  2172. : String(r.String)
  2173. {
  2174. }
  2175. private:
  2176. std::string String;
  2177. bool Search(std::string const& parent, cmFileList& lister) override
  2178. {
  2179. // Look for matching files.
  2180. std::vector<std::string> matches;
  2181. cmsys::Directory d;
  2182. d.Load(parent);
  2183. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  2184. const char* fname = d.GetFile(i);
  2185. if (this->IsIgnoredEntry(fname)) {
  2186. continue;
  2187. }
  2188. if (cmsysString_strcasecmp(fname, this->String.c_str()) == 0) {
  2189. if (this->Consider(parent + fname, lister)) {
  2190. return true;
  2191. }
  2192. }
  2193. }
  2194. return false;
  2195. }
  2196. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  2197. {
  2198. std::unique_ptr<cmFileListGeneratorBase> g(
  2199. new cmFileListGeneratorCaseInsensitive(*this));
  2200. return g;
  2201. }
  2202. };
  2203. class cmFileListGeneratorGlob : public cmFileListGeneratorBase
  2204. {
  2205. public:
  2206. cmFileListGeneratorGlob(std::string str)
  2207. : Pattern(std::move(str))
  2208. {
  2209. }
  2210. cmFileListGeneratorGlob(cmFileListGeneratorGlob const& r)
  2211. : Pattern(r.Pattern)
  2212. {
  2213. }
  2214. private:
  2215. std::string Pattern;
  2216. bool Search(std::string const& parent, cmFileList& lister) override
  2217. {
  2218. // Glob the set of matching files.
  2219. std::string expr = cmStrCat(parent, this->Pattern);
  2220. cmsys::Glob g;
  2221. if (!g.FindFiles(expr)) {
  2222. return false;
  2223. }
  2224. std::vector<std::string> const& files = g.GetFiles();
  2225. // Look for directories among the matches.
  2226. return std::any_of(files.cbegin(), files.cend(),
  2227. [this, &lister](std::string const& f) {
  2228. return this->Consider(f, lister);
  2229. });
  2230. }
  2231. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  2232. {
  2233. return cm::make_unique<cmFileListGeneratorGlob>(*this);
  2234. }
  2235. };
  2236. } // anonymous namespace
  2237. // END File paths generators
  2238. bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
  2239. {
  2240. assert(!prefix_in.empty() && prefix_in.back() == '/');
  2241. // Skip this if the prefix does not exist.
  2242. if (!cmSystemTools::FileIsDirectory(prefix_in)) {
  2243. return false;
  2244. }
  2245. // Skip this if it's in ignored paths.
  2246. std::string prefixWithoutSlash = prefix_in;
  2247. if (prefixWithoutSlash != "/" && prefixWithoutSlash.back() == '/') {
  2248. prefixWithoutSlash.erase(prefixWithoutSlash.length() - 1);
  2249. }
  2250. if (this->IgnoredPaths.count(prefixWithoutSlash) ||
  2251. this->IgnoredPrefixPaths.count(prefixWithoutSlash)) {
  2252. return false;
  2253. }
  2254. // PREFIX/ (useful on windows or in build trees)
  2255. if (this->SearchDirectory(prefix_in)) {
  2256. return true;
  2257. }
  2258. // Strip the trailing slash because the path generator is about to
  2259. // add one.
  2260. std::string const prefix = prefix_in.substr(0, prefix_in.size() - 1);
  2261. auto searchFn = [this](const std::string& fullPath) -> bool {
  2262. return this->SearchDirectory(fullPath);
  2263. };
  2264. // PREFIX/(cmake|CMake)/ (useful on windows or in build trees)
  2265. {
  2266. cmFindPackageFileList lister(searchFn);
  2267. lister / cmFileListGeneratorFixed(prefix) /
  2268. cmFileListGeneratorCaseInsensitive("cmake");
  2269. if (lister.Search()) {
  2270. return true;
  2271. }
  2272. }
  2273. // PREFIX/(Foo|foo|FOO).*/
  2274. {
  2275. cmFindPackageFileList lister(searchFn);
  2276. lister / cmFileListGeneratorFixed(prefix) /
  2277. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2278. this->SortDirection);
  2279. if (lister.Search()) {
  2280. return true;
  2281. }
  2282. }
  2283. // PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/
  2284. {
  2285. cmFindPackageFileList lister(searchFn);
  2286. lister / cmFileListGeneratorFixed(prefix) /
  2287. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2288. this->SortDirection) /
  2289. cmFileListGeneratorCaseInsensitive("cmake");
  2290. if (lister.Search()) {
  2291. return true;
  2292. }
  2293. }
  2294. // Construct list of common install locations (lib and share).
  2295. std::vector<std::string> common;
  2296. if (!this->LibraryArchitecture.empty()) {
  2297. common.push_back("lib/" + this->LibraryArchitecture);
  2298. }
  2299. if (this->UseLib32Paths) {
  2300. common.emplace_back("lib32");
  2301. }
  2302. if (this->UseLib64Paths) {
  2303. common.emplace_back("lib64");
  2304. }
  2305. if (this->UseLibx32Paths) {
  2306. common.emplace_back("libx32");
  2307. }
  2308. common.emplace_back("lib");
  2309. common.emplace_back("share");
  2310. // PREFIX/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  2311. {
  2312. cmFindPackageFileList lister(searchFn);
  2313. lister / cmFileListGeneratorFixed(prefix) /
  2314. cmFileListGeneratorEnumerate(common) /
  2315. cmFileListGeneratorFixed("cmake") /
  2316. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2317. this->SortDirection);
  2318. if (lister.Search()) {
  2319. return true;
  2320. }
  2321. }
  2322. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  2323. {
  2324. cmFindPackageFileList lister(searchFn);
  2325. lister / cmFileListGeneratorFixed(prefix) /
  2326. cmFileListGeneratorEnumerate(common) /
  2327. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2328. this->SortDirection);
  2329. if (lister.Search()) {
  2330. return true;
  2331. }
  2332. }
  2333. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  2334. {
  2335. cmFindPackageFileList lister(searchFn);
  2336. lister / cmFileListGeneratorFixed(prefix) /
  2337. cmFileListGeneratorEnumerate(common) /
  2338. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2339. this->SortDirection) /
  2340. cmFileListGeneratorCaseInsensitive("cmake");
  2341. if (lister.Search()) {
  2342. return true;
  2343. }
  2344. }
  2345. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  2346. {
  2347. cmFindPackageFileList lister(searchFn);
  2348. lister / cmFileListGeneratorFixed(prefix) /
  2349. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2350. this->SortDirection) /
  2351. cmFileListGeneratorEnumerate(common) /
  2352. cmFileListGeneratorFixed("cmake") /
  2353. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2354. this->SortDirection);
  2355. if (lister.Search()) {
  2356. return true;
  2357. }
  2358. }
  2359. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  2360. {
  2361. cmFindPackageFileList lister(searchFn);
  2362. lister / cmFileListGeneratorFixed(prefix) /
  2363. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2364. this->SortDirection) /
  2365. cmFileListGeneratorEnumerate(common) /
  2366. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2367. this->SortDirection);
  2368. if (lister.Search()) {
  2369. return true;
  2370. }
  2371. }
  2372. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  2373. {
  2374. cmFindPackageFileList lister(searchFn);
  2375. lister / cmFileListGeneratorFixed(prefix) /
  2376. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2377. this->SortDirection) /
  2378. cmFileListGeneratorEnumerate(common) /
  2379. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2380. this->SortDirection) /
  2381. cmFileListGeneratorCaseInsensitive("cmake");
  2382. if (lister.Search()) {
  2383. return true;
  2384. }
  2385. }
  2386. return false;
  2387. }
  2388. bool cmFindPackageCommand::SearchFrameworkPrefix(std::string const& prefix_in)
  2389. {
  2390. assert(!prefix_in.empty() && prefix_in.back() == '/');
  2391. // Strip the trailing slash because the path generator is about to
  2392. // add one.
  2393. std::string const prefix = prefix_in.substr(0, prefix_in.size() - 1);
  2394. auto searchFn = [this](const std::string& fullPath) -> bool {
  2395. return this->SearchDirectory(fullPath);
  2396. };
  2397. // <prefix>/Foo.framework/Resources/
  2398. {
  2399. cmFindPackageFileList lister(searchFn);
  2400. lister / cmFileListGeneratorFixed(prefix) /
  2401. cmFileListGeneratorMacProject(this->Names, ".framework") /
  2402. cmFileListGeneratorFixed("Resources");
  2403. if (lister.Search()) {
  2404. return true;
  2405. }
  2406. }
  2407. // <prefix>/Foo.framework/Resources/CMake/
  2408. {
  2409. cmFindPackageFileList lister(searchFn);
  2410. lister / cmFileListGeneratorFixed(prefix) /
  2411. cmFileListGeneratorMacProject(this->Names, ".framework") /
  2412. cmFileListGeneratorFixed("Resources") /
  2413. cmFileListGeneratorCaseInsensitive("cmake");
  2414. if (lister.Search()) {
  2415. return true;
  2416. }
  2417. }
  2418. // <prefix>/Foo.framework/Versions/*/Resources/
  2419. {
  2420. cmFindPackageFileList lister(searchFn);
  2421. lister / cmFileListGeneratorFixed(prefix) /
  2422. cmFileListGeneratorMacProject(this->Names, ".framework") /
  2423. cmFileListGeneratorFixed("Versions") /
  2424. cmFileListGeneratorGlob("*/Resources");
  2425. if (lister.Search()) {
  2426. return true;
  2427. }
  2428. }
  2429. // <prefix>/Foo.framework/Versions/*/Resources/CMake/
  2430. {
  2431. cmFindPackageFileList lister(searchFn);
  2432. lister / cmFileListGeneratorFixed(prefix) /
  2433. cmFileListGeneratorMacProject(this->Names, ".framework") /
  2434. cmFileListGeneratorFixed("Versions") /
  2435. cmFileListGeneratorGlob("*/Resources") /
  2436. cmFileListGeneratorCaseInsensitive("cmake");
  2437. if (lister.Search()) {
  2438. return true;
  2439. }
  2440. }
  2441. return false;
  2442. }
  2443. bool cmFindPackageCommand::SearchAppBundlePrefix(std::string const& prefix_in)
  2444. {
  2445. assert(!prefix_in.empty() && prefix_in.back() == '/');
  2446. // Strip the trailing slash because the path generator is about to
  2447. // add one.
  2448. std::string const prefix = prefix_in.substr(0, prefix_in.size() - 1);
  2449. auto searchFn = [this](const std::string& fullPath) -> bool {
  2450. return this->SearchDirectory(fullPath);
  2451. };
  2452. // <prefix>/Foo.app/Contents/Resources
  2453. {
  2454. cmFindPackageFileList lister(searchFn);
  2455. lister / cmFileListGeneratorFixed(prefix) /
  2456. cmFileListGeneratorMacProject(this->Names, ".app") /
  2457. cmFileListGeneratorFixed("Contents/Resources");
  2458. if (lister.Search()) {
  2459. return true;
  2460. }
  2461. }
  2462. // <prefix>/Foo.app/Contents/Resources/CMake
  2463. {
  2464. cmFindPackageFileList lister(searchFn);
  2465. lister / cmFileListGeneratorFixed(prefix) /
  2466. cmFileListGeneratorMacProject(this->Names, ".app") /
  2467. cmFileListGeneratorFixed("Contents/Resources") /
  2468. cmFileListGeneratorCaseInsensitive("cmake");
  2469. if (lister.Search()) {
  2470. return true;
  2471. }
  2472. }
  2473. return false;
  2474. }
  2475. // TODO: Debug cmsys::Glob double slash problem.
  2476. bool cmFindPackage(std::vector<std::string> const& args,
  2477. cmExecutionStatus& status)
  2478. {
  2479. return cmFindPackageCommand(status).InitialPass(args);
  2480. }