cmFindPackageCommand.cxx 71 KB

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