cmFindPackageCommand.cxx 87 KB

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