cmFindPackageCommand.cxx 84 KB

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