cmFindPackageCommand.cxx 84 KB

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