cmFindPackageCommand.cxx 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281
  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. if (this->UseFindModules) {
  458. bool foundModule = false;
  459. if (!this->FindModule(foundModule)) {
  460. this->AppendSuccessInformation();
  461. return false;
  462. }
  463. if (foundModule) {
  464. this->AppendSuccessInformation();
  465. return true;
  466. }
  467. }
  468. if (this->UseFindModules && this->UseConfigFiles &&
  469. this->Makefile->IsOn("CMAKE_FIND_PACKAGE_WARN_NO_MODULE")) {
  470. std::ostringstream aw;
  471. if (this->RequiredCMakeVersion >= CMake_VERSION_ENCODE(2, 8, 8)) {
  472. aw << "find_package called without either MODULE or CONFIG option and "
  473. "no Find"
  474. << this->Name
  475. << ".cmake module is in CMAKE_MODULE_PATH. "
  476. "Add MODULE to exclusively request Module mode and fail if "
  477. "Find"
  478. << this->Name
  479. << ".cmake is missing. "
  480. "Add CONFIG to exclusively request Config mode and search for a "
  481. "package configuration file provided by "
  482. << this->Name << " (" << this->Name << "Config.cmake or "
  483. << cmSystemTools::LowerCase(this->Name) << "-config.cmake). ";
  484. } else {
  485. aw
  486. << "find_package called without NO_MODULE option and no "
  487. "Find"
  488. << this->Name
  489. << ".cmake module is in CMAKE_MODULE_PATH. "
  490. "Add NO_MODULE to exclusively request Config mode and search for a "
  491. "package configuration file provided by "
  492. << this->Name << " (" << this->Name << "Config.cmake or "
  493. << cmSystemTools::LowerCase(this->Name)
  494. << "-config.cmake). "
  495. "Otherwise make Find"
  496. << this->Name
  497. << ".cmake available in "
  498. "CMAKE_MODULE_PATH.";
  499. }
  500. aw << "\n"
  501. "(Variable CMAKE_FIND_PACKAGE_WARN_NO_MODULE enabled this warning.)";
  502. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
  503. }
  504. // No find module. Assume the project has a CMake config file. Use
  505. // a <PackageName>_DIR cache variable to locate it.
  506. this->Variable = this->Name;
  507. this->Variable += "_DIR";
  508. // Add the default name.
  509. if (this->Names.empty()) {
  510. this->Names.push_back(this->Name);
  511. }
  512. // Add the default configs.
  513. if (this->Configs.empty()) {
  514. for (std::string const& n : this->Names) {
  515. std::string config = n;
  516. config += "Config.cmake";
  517. this->Configs.push_back(config);
  518. config = cmSystemTools::LowerCase(n);
  519. config += "-config.cmake";
  520. this->Configs.push_back(std::move(config));
  521. }
  522. }
  523. // get igonored paths from vars and reroot them.
  524. std::vector<std::string> ignored;
  525. this->GetIgnoredPaths(ignored);
  526. this->RerootPaths(ignored);
  527. // Construct a set of ignored paths
  528. this->IgnoredPaths.clear();
  529. this->IgnoredPaths.insert(ignored.begin(), ignored.end());
  530. // Find and load the package.
  531. bool result = this->HandlePackageMode();
  532. this->AppendSuccessInformation();
  533. return result;
  534. }
  535. void cmFindPackageCommand::SetModuleVariables(const std::string& components)
  536. {
  537. this->AddFindDefinition("CMAKE_FIND_PACKAGE_NAME", this->Name.c_str());
  538. // Store the list of components.
  539. std::string components_var = this->Name + "_FIND_COMPONENTS";
  540. this->AddFindDefinition(components_var, components.c_str());
  541. if (this->Quiet) {
  542. // Tell the module that is about to be read that it should find
  543. // quietly.
  544. std::string quietly = this->Name;
  545. quietly += "_FIND_QUIETLY";
  546. this->AddFindDefinition(quietly, "1");
  547. }
  548. if (this->Required) {
  549. // Tell the module that is about to be read that it should report
  550. // a fatal error if the package is not found.
  551. std::string req = this->Name;
  552. req += "_FIND_REQUIRED";
  553. this->AddFindDefinition(req, "1");
  554. }
  555. if (!this->Version.empty()) {
  556. // Tell the module that is about to be read what version of the
  557. // package has been requested.
  558. std::string ver = this->Name;
  559. ver += "_FIND_VERSION";
  560. this->AddFindDefinition(ver, this->Version.c_str());
  561. char buf[64];
  562. sprintf(buf, "%u", this->VersionMajor);
  563. this->AddFindDefinition(ver + "_MAJOR", buf);
  564. sprintf(buf, "%u", this->VersionMinor);
  565. this->AddFindDefinition(ver + "_MINOR", buf);
  566. sprintf(buf, "%u", this->VersionPatch);
  567. this->AddFindDefinition(ver + "_PATCH", buf);
  568. sprintf(buf, "%u", this->VersionTweak);
  569. this->AddFindDefinition(ver + "_TWEAK", buf);
  570. sprintf(buf, "%u", this->VersionCount);
  571. this->AddFindDefinition(ver + "_COUNT", buf);
  572. // Tell the module whether an exact version has been requested.
  573. std::string exact = this->Name;
  574. exact += "_FIND_VERSION_EXACT";
  575. this->AddFindDefinition(exact, this->VersionExact ? "1" : "0");
  576. }
  577. }
  578. void cmFindPackageCommand::AddFindDefinition(const std::string& var,
  579. const char* val)
  580. {
  581. if (const char* old = this->Makefile->GetDefinition(var)) {
  582. this->OriginalDefs[var].exists = true;
  583. this->OriginalDefs[var].value = old;
  584. } else {
  585. this->OriginalDefs[var].exists = false;
  586. }
  587. this->Makefile->AddDefinition(var, val);
  588. }
  589. void cmFindPackageCommand::RestoreFindDefinitions()
  590. {
  591. for (auto const& i : this->OriginalDefs) {
  592. OriginalDef const& od = i.second;
  593. if (od.exists) {
  594. this->Makefile->AddDefinition(i.first, od.value.c_str());
  595. } else {
  596. this->Makefile->RemoveDefinition(i.first);
  597. }
  598. }
  599. }
  600. bool cmFindPackageCommand::FindModule(bool& found)
  601. {
  602. std::string module = "Find";
  603. module += this->Name;
  604. module += ".cmake";
  605. bool system = false;
  606. std::string mfile = this->Makefile->GetModulesFile(module, system);
  607. if (!mfile.empty()) {
  608. if (system) {
  609. auto it = this->DeprecatedFindModules.find(this->Name);
  610. if (it != this->DeprecatedFindModules.end()) {
  611. cmPolicies::PolicyStatus status =
  612. this->Makefile->GetPolicyStatus(it->second);
  613. switch (status) {
  614. case cmPolicies::WARN: {
  615. std::ostringstream e;
  616. e << cmPolicies::GetPolicyWarning(it->second) << "\n";
  617. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  618. CM_FALLTHROUGH;
  619. }
  620. case cmPolicies::OLD:
  621. break;
  622. case cmPolicies::REQUIRED_IF_USED:
  623. case cmPolicies::REQUIRED_ALWAYS:
  624. case cmPolicies::NEW:
  625. return true;
  626. }
  627. }
  628. }
  629. // Load the module we found, and set "<name>_FIND_MODULE" to true
  630. // while inside it.
  631. found = true;
  632. std::string var = this->Name;
  633. var += "_FIND_MODULE";
  634. this->Makefile->AddDefinition(var, "1");
  635. bool result = this->ReadListFile(mfile, DoPolicyScope);
  636. this->Makefile->RemoveDefinition(var);
  637. return result;
  638. }
  639. return true;
  640. }
  641. bool cmFindPackageCommand::HandlePackageMode()
  642. {
  643. this->ConsideredConfigs.clear();
  644. // Support old capitalization behavior.
  645. std::string upperDir = cmSystemTools::UpperCase(this->Name);
  646. std::string upperFound = cmSystemTools::UpperCase(this->Name);
  647. upperDir += "_DIR";
  648. upperFound += "_FOUND";
  649. // Try to find the config file.
  650. const char* def = this->Makefile->GetDefinition(this->Variable);
  651. // Try to load the config file if the directory is known
  652. bool fileFound = false;
  653. if (this->UseConfigFiles) {
  654. if (!cmSystemTools::IsOff(def)) {
  655. // Get the directory from the variable value.
  656. std::string dir = def;
  657. cmSystemTools::ConvertToUnixSlashes(dir);
  658. // Treat relative paths with respect to the current source dir.
  659. if (!cmSystemTools::FileIsFullPath(dir)) {
  660. dir = "/" + dir;
  661. dir = this->Makefile->GetCurrentSourceDirectory() + dir;
  662. }
  663. // The file location was cached. Look for the correct file.
  664. std::string file;
  665. if (this->FindConfigFile(dir, file)) {
  666. this->FileFound = file;
  667. fileFound = true;
  668. }
  669. def = this->Makefile->GetDefinition(this->Variable);
  670. }
  671. // Search for the config file if it is not already found.
  672. if (cmSystemTools::IsOff(def) || !fileFound) {
  673. fileFound = this->FindConfig();
  674. }
  675. // Sanity check.
  676. if (fileFound && this->FileFound.empty()) {
  677. this->Makefile->IssueMessage(
  678. MessageType::INTERNAL_ERROR,
  679. "fileFound is true but FileFound is empty!");
  680. fileFound = false;
  681. }
  682. }
  683. std::string foundVar = this->Name;
  684. foundVar += "_FOUND";
  685. std::string notFoundMessageVar = this->Name;
  686. notFoundMessageVar += "_NOT_FOUND_MESSAGE";
  687. std::string notFoundMessage;
  688. // If the directory for the config file was found, try to read the file.
  689. bool result = true;
  690. bool found = false;
  691. bool configFileSetFOUNDFalse = false;
  692. if (fileFound) {
  693. if (this->Makefile->IsDefinitionSet(foundVar) &&
  694. !this->Makefile->IsOn(foundVar)) {
  695. // by removing Foo_FOUND here if it is FALSE, we don't really change
  696. // the situation for the Config file which is about to be included,
  697. // but we make it possible to detect later on whether the Config file
  698. // has set Foo_FOUND to FALSE itself:
  699. this->Makefile->RemoveDefinition(foundVar);
  700. }
  701. this->Makefile->RemoveDefinition(notFoundMessageVar);
  702. // Set the version variables before loading the config file.
  703. // It may override them.
  704. this->StoreVersionFound();
  705. // Parse the configuration file.
  706. if (this->ReadListFile(this->FileFound, DoPolicyScope)) {
  707. // The package has been found.
  708. found = true;
  709. // Check whether the Config file has set Foo_FOUND to FALSE:
  710. if (this->Makefile->IsDefinitionSet(foundVar) &&
  711. !this->Makefile->IsOn(foundVar)) {
  712. // we get here if the Config file has set Foo_FOUND actively to FALSE
  713. found = false;
  714. configFileSetFOUNDFalse = true;
  715. notFoundMessage =
  716. this->Makefile->GetSafeDefinition(notFoundMessageVar);
  717. }
  718. } else {
  719. // The configuration file is invalid.
  720. result = false;
  721. }
  722. }
  723. // package not found
  724. if (result && !found) {
  725. // warn if package required or neither quiet nor in config mode
  726. if (this->Required ||
  727. !(this->Quiet ||
  728. (this->UseConfigFiles && !this->UseFindModules &&
  729. this->ConsideredConfigs.empty()))) {
  730. // The variable is not set.
  731. std::ostringstream e;
  732. std::ostringstream aw;
  733. if (configFileSetFOUNDFalse) {
  734. /* clang-format off */
  735. e << "Found package configuration file:\n"
  736. " " << this->FileFound << "\n"
  737. "but it set " << foundVar << " to FALSE so package \"" <<
  738. this->Name << "\" is considered to be NOT FOUND.";
  739. /* clang-format on */
  740. if (!notFoundMessage.empty()) {
  741. e << " Reason given by package: \n" << notFoundMessage << "\n";
  742. }
  743. }
  744. // If there are files in ConsideredConfigs, it means that FooConfig.cmake
  745. // have been found, but they didn't have appropriate versions.
  746. else if (!this->ConsideredConfigs.empty()) {
  747. std::vector<ConfigFileInfo>::const_iterator duplicate_end =
  748. cmRemoveDuplicates(this->ConsideredConfigs);
  749. e << "Could not find a configuration file for package \"" << this->Name
  750. << "\" that "
  751. << (this->VersionExact ? "exactly matches" : "is compatible with")
  752. << " requested version \"" << this->Version << "\".\n"
  753. << "The following configuration files were considered but not "
  754. "accepted:\n";
  755. for (ConfigFileInfo const& info :
  756. cmMakeRange(this->ConsideredConfigs.cbegin(), duplicate_end)) {
  757. e << " " << info.filename << ", version: " << info.version << "\n";
  758. }
  759. } else {
  760. std::string requestedVersionString;
  761. if (!this->Version.empty()) {
  762. requestedVersionString = " (requested version ";
  763. requestedVersionString += this->Version;
  764. requestedVersionString += ")";
  765. }
  766. if (this->UseConfigFiles) {
  767. if (this->UseFindModules) {
  768. e << "By not providing \"Find" << this->Name
  769. << ".cmake\" in "
  770. "CMAKE_MODULE_PATH this project has asked CMake to find a "
  771. "package configuration file provided by \""
  772. << this->Name
  773. << "\", "
  774. "but CMake did not find one.\n";
  775. }
  776. if (this->Configs.size() == 1) {
  777. e << "Could not find a package configuration file named \""
  778. << this->Configs[0] << "\" provided by package \"" << this->Name
  779. << "\"" << requestedVersionString << ".\n";
  780. } else {
  781. e << "Could not find a package configuration file provided by \""
  782. << this->Name << "\"" << requestedVersionString
  783. << " with any of the following names:\n"
  784. << cmWrap(" ", this->Configs, "", "\n") << "\n";
  785. }
  786. e << "Add the installation prefix of \"" << this->Name
  787. << "\" to "
  788. "CMAKE_PREFIX_PATH or set \""
  789. << this->Variable
  790. << "\" to a "
  791. "directory containing one of the above files. "
  792. "If \""
  793. << this->Name
  794. << "\" provides a separate development "
  795. "package or SDK, be sure it has been installed.";
  796. } else // if(!this->UseFindModules && !this->UseConfigFiles)
  797. {
  798. e << "No \"Find" << this->Name << ".cmake\" found in "
  799. << "CMAKE_MODULE_PATH.";
  800. aw
  801. << "Find" << this->Name
  802. << ".cmake must either be part of this "
  803. "project itself, in this case adjust CMAKE_MODULE_PATH so that "
  804. "it points to the correct location inside its source tree.\n"
  805. "Or it must be installed by a package which has already been "
  806. "found via find_package(). In this case make sure that "
  807. "package has indeed been found and adjust CMAKE_MODULE_PATH to "
  808. "contain the location where that package has installed "
  809. "Find"
  810. << this->Name
  811. << ".cmake. This must be a location "
  812. "provided by that package. This error in general means that "
  813. "the buildsystem of this project is relying on a Find-module "
  814. "without ensuring that it is actually available.\n";
  815. }
  816. }
  817. this->Makefile->IssueMessage(this->Required ? MessageType::FATAL_ERROR
  818. : MessageType::WARNING,
  819. e.str());
  820. if (this->Required) {
  821. cmSystemTools::SetFatalErrorOccured();
  822. }
  823. if (!aw.str().empty()) {
  824. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
  825. }
  826. }
  827. // output result if in config mode but not in quiet mode
  828. else if (!this->Quiet) {
  829. std::ostringstream aw;
  830. aw << "Could NOT find " << this->Name << " (missing: " << this->Name
  831. << "_DIR)";
  832. this->Makefile->DisplayStatus(aw.str(), -1);
  833. }
  834. }
  835. // Set a variable marking whether the package was found.
  836. this->Makefile->AddDefinition(foundVar, found ? "1" : "0");
  837. // Set a variable naming the configuration file that was found.
  838. std::string fileVar = this->Name;
  839. fileVar += "_CONFIG";
  840. if (found) {
  841. this->Makefile->AddDefinition(fileVar, this->FileFound.c_str());
  842. } else {
  843. this->Makefile->RemoveDefinition(fileVar);
  844. }
  845. std::string consideredConfigsVar = this->Name;
  846. consideredConfigsVar += "_CONSIDERED_CONFIGS";
  847. std::string consideredVersionsVar = this->Name;
  848. consideredVersionsVar += "_CONSIDERED_VERSIONS";
  849. std::string consideredConfigFiles;
  850. std::string consideredVersions;
  851. const char* sep = "";
  852. for (ConfigFileInfo const& i : this->ConsideredConfigs) {
  853. consideredConfigFiles += sep;
  854. consideredVersions += sep;
  855. consideredConfigFiles += i.filename;
  856. consideredVersions += i.version;
  857. sep = ";";
  858. }
  859. this->Makefile->AddDefinition(consideredConfigsVar,
  860. consideredConfigFiles.c_str());
  861. this->Makefile->AddDefinition(consideredVersionsVar,
  862. consideredVersions.c_str());
  863. return result;
  864. }
  865. bool cmFindPackageCommand::FindConfig()
  866. {
  867. // Compute the set of search prefixes.
  868. this->ComputePrefixes();
  869. // Look for the project's configuration file.
  870. bool found = false;
  871. // Search for frameworks.
  872. if (!found && (this->SearchFrameworkFirst || this->SearchFrameworkOnly)) {
  873. found = this->FindFrameworkConfig();
  874. }
  875. // Search for apps.
  876. if (!found && (this->SearchAppBundleFirst || this->SearchAppBundleOnly)) {
  877. found = this->FindAppBundleConfig();
  878. }
  879. // Search prefixes.
  880. if (!found && !(this->SearchFrameworkOnly || this->SearchAppBundleOnly)) {
  881. found = this->FindPrefixedConfig();
  882. }
  883. // Search for frameworks.
  884. if (!found && this->SearchFrameworkLast) {
  885. found = this->FindFrameworkConfig();
  886. }
  887. // Search for apps.
  888. if (!found && this->SearchAppBundleLast) {
  889. found = this->FindAppBundleConfig();
  890. }
  891. // Store the entry in the cache so it can be set by the user.
  892. std::string init;
  893. if (found) {
  894. init = cmSystemTools::GetFilenamePath(this->FileFound);
  895. } else {
  896. init = this->Variable + "-NOTFOUND";
  897. }
  898. std::string help =
  899. "The directory containing a CMake configuration file for ";
  900. help += this->Name;
  901. help += ".";
  902. // We force the value since we do not get here if it was already set.
  903. this->Makefile->AddCacheDefinition(this->Variable, init.c_str(),
  904. help.c_str(), cmStateEnums::PATH, true);
  905. return found;
  906. }
  907. bool cmFindPackageCommand::FindPrefixedConfig()
  908. {
  909. std::vector<std::string> const& prefixes = this->SearchPaths;
  910. for (std::string const& p : prefixes) {
  911. if (this->SearchPrefix(p)) {
  912. return true;
  913. }
  914. }
  915. return false;
  916. }
  917. bool cmFindPackageCommand::FindFrameworkConfig()
  918. {
  919. std::vector<std::string> const& prefixes = this->SearchPaths;
  920. for (std::string const& p : prefixes) {
  921. if (this->SearchFrameworkPrefix(p)) {
  922. return true;
  923. }
  924. }
  925. return false;
  926. }
  927. bool cmFindPackageCommand::FindAppBundleConfig()
  928. {
  929. std::vector<std::string> const& prefixes = this->SearchPaths;
  930. for (std::string const& p : prefixes) {
  931. if (this->SearchAppBundlePrefix(p)) {
  932. return true;
  933. }
  934. }
  935. return false;
  936. }
  937. bool cmFindPackageCommand::ReadListFile(const std::string& f,
  938. PolicyScopeRule psr)
  939. {
  940. const bool noPolicyScope = !this->PolicyScope || psr == NoPolicyScope;
  941. if (this->Makefile->ReadDependentFile(f, noPolicyScope)) {
  942. return true;
  943. }
  944. std::string e = "Error reading CMake code from \"";
  945. e += f;
  946. e += "\".";
  947. this->SetError(e);
  948. return false;
  949. }
  950. void cmFindPackageCommand::AppendToFoundProperty(bool found)
  951. {
  952. std::vector<std::string> foundContents;
  953. const char* foundProp =
  954. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_FOUND");
  955. if (foundProp && *foundProp) {
  956. std::string tmp = foundProp;
  957. cmSystemTools::ExpandListArgument(tmp, foundContents, false);
  958. std::vector<std::string>::iterator nameIt =
  959. std::find(foundContents.begin(), foundContents.end(), this->Name);
  960. if (nameIt != foundContents.end()) {
  961. foundContents.erase(nameIt);
  962. }
  963. }
  964. std::vector<std::string> notFoundContents;
  965. const char* notFoundProp =
  966. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_NOT_FOUND");
  967. if (notFoundProp && *notFoundProp) {
  968. std::string tmp = notFoundProp;
  969. cmSystemTools::ExpandListArgument(tmp, notFoundContents, false);
  970. std::vector<std::string>::iterator nameIt =
  971. std::find(notFoundContents.begin(), notFoundContents.end(), this->Name);
  972. if (nameIt != notFoundContents.end()) {
  973. notFoundContents.erase(nameIt);
  974. }
  975. }
  976. if (found) {
  977. foundContents.push_back(this->Name);
  978. } else {
  979. notFoundContents.push_back(this->Name);
  980. }
  981. std::string tmp = cmJoin(foundContents, ";");
  982. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_FOUND", tmp.c_str());
  983. tmp = cmJoin(notFoundContents, ";");
  984. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_NOT_FOUND",
  985. tmp.c_str());
  986. }
  987. void cmFindPackageCommand::AppendSuccessInformation()
  988. {
  989. {
  990. std::string transitivePropName = "_CMAKE_";
  991. transitivePropName += this->Name + "_TRANSITIVE_DEPENDENCY";
  992. this->Makefile->GetState()->SetGlobalProperty(transitivePropName, "False");
  993. }
  994. std::string found = this->Name;
  995. found += "_FOUND";
  996. std::string upperFound = cmSystemTools::UpperCase(found);
  997. const char* upperResult = this->Makefile->GetDefinition(upperFound);
  998. const char* result = this->Makefile->GetDefinition(found);
  999. bool packageFound =
  1000. ((cmSystemTools::IsOn(result)) || (cmSystemTools::IsOn(upperResult)));
  1001. this->AppendToFoundProperty(packageFound);
  1002. // Record whether the find was quiet or not, so this can be used
  1003. // e.g. in FeatureSummary.cmake
  1004. std::string quietInfoPropName = "_CMAKE_";
  1005. quietInfoPropName += this->Name;
  1006. quietInfoPropName += "_QUIET";
  1007. this->Makefile->GetState()->SetGlobalProperty(
  1008. quietInfoPropName, this->Quiet ? "TRUE" : "FALSE");
  1009. // set a global property to record the required version of this package
  1010. std::string versionInfoPropName = "_CMAKE_";
  1011. versionInfoPropName += this->Name;
  1012. versionInfoPropName += "_REQUIRED_VERSION";
  1013. std::string versionInfo;
  1014. if (!this->Version.empty()) {
  1015. versionInfo = this->VersionExact ? "==" : ">=";
  1016. versionInfo += " ";
  1017. versionInfo += this->Version;
  1018. }
  1019. this->Makefile->GetState()->SetGlobalProperty(versionInfoPropName,
  1020. versionInfo.c_str());
  1021. if (this->Required) {
  1022. std::string requiredInfoPropName = "_CMAKE_";
  1023. requiredInfoPropName += this->Name;
  1024. requiredInfoPropName += "_TYPE";
  1025. this->Makefile->GetState()->SetGlobalProperty(requiredInfoPropName,
  1026. "REQUIRED");
  1027. }
  1028. // Restore original state of "_FIND_" variables we set.
  1029. this->RestoreFindDefinitions();
  1030. // Pop the package stack
  1031. this->Makefile->FindPackageRootPathStack.pop_back();
  1032. }
  1033. void cmFindPackageCommand::ComputePrefixes()
  1034. {
  1035. if (!this->NoDefaultPath) {
  1036. if (!this->NoPackageRootPath) {
  1037. this->FillPrefixesPackageRoot();
  1038. }
  1039. if (!this->NoCMakePath) {
  1040. this->FillPrefixesCMakeVariable();
  1041. }
  1042. if (!this->NoCMakeEnvironmentPath) {
  1043. this->FillPrefixesCMakeEnvironment();
  1044. }
  1045. }
  1046. this->FillPrefixesUserHints();
  1047. if (!this->NoDefaultPath) {
  1048. if (!this->NoSystemEnvironmentPath) {
  1049. this->FillPrefixesSystemEnvironment();
  1050. }
  1051. if (!this->NoUserRegistry) {
  1052. this->FillPrefixesUserRegistry();
  1053. }
  1054. if (!this->NoCMakeSystemPath) {
  1055. this->FillPrefixesCMakeSystemVariable();
  1056. }
  1057. if (!this->NoSystemRegistry) {
  1058. this->FillPrefixesSystemRegistry();
  1059. }
  1060. }
  1061. this->FillPrefixesUserGuess();
  1062. this->ComputeFinalPaths();
  1063. }
  1064. void cmFindPackageCommand::FillPrefixesPackageRoot()
  1065. {
  1066. cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRoot];
  1067. // Add the PACKAGE_ROOT_PATH from each enclosing find_package call.
  1068. for (std::deque<std::vector<std::string>>::const_reverse_iterator pkgPaths =
  1069. this->Makefile->FindPackageRootPathStack.rbegin();
  1070. pkgPaths != this->Makefile->FindPackageRootPathStack.rend();
  1071. ++pkgPaths) {
  1072. for (std::string const& path : *pkgPaths) {
  1073. paths.AddPath(path);
  1074. }
  1075. }
  1076. }
  1077. void cmFindPackageCommand::FillPrefixesCMakeEnvironment()
  1078. {
  1079. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeEnvironment];
  1080. // Check the environment variable with the same name as the cache
  1081. // entry.
  1082. paths.AddEnvPath(this->Variable);
  1083. // And now the general CMake environment variables
  1084. paths.AddEnvPath("CMAKE_PREFIX_PATH");
  1085. paths.AddEnvPath("CMAKE_FRAMEWORK_PATH");
  1086. paths.AddEnvPath("CMAKE_APPBUNDLE_PATH");
  1087. }
  1088. void cmFindPackageCommand::FillPrefixesCMakeVariable()
  1089. {
  1090. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMake];
  1091. paths.AddCMakePath("CMAKE_PREFIX_PATH");
  1092. paths.AddCMakePath("CMAKE_FRAMEWORK_PATH");
  1093. paths.AddCMakePath("CMAKE_APPBUNDLE_PATH");
  1094. }
  1095. void cmFindPackageCommand::FillPrefixesSystemEnvironment()
  1096. {
  1097. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemEnvironment];
  1098. // Use the system search path to generate prefixes.
  1099. // Relative paths are interpreted with respect to the current
  1100. // working directory.
  1101. std::vector<std::string> tmp;
  1102. cmSystemTools::GetPath(tmp);
  1103. for (std::string const& i : tmp) {
  1104. // If the path is a PREFIX/bin case then add its parent instead.
  1105. if ((cmHasLiteralSuffix(i, "/bin")) || (cmHasLiteralSuffix(i, "/sbin"))) {
  1106. paths.AddPath(cmSystemTools::GetFilenamePath(i));
  1107. } else {
  1108. paths.AddPath(i);
  1109. }
  1110. }
  1111. }
  1112. void cmFindPackageCommand::FillPrefixesUserRegistry()
  1113. {
  1114. #if defined(_WIN32) && !defined(__CYGWIN__)
  1115. this->LoadPackageRegistryWinUser();
  1116. #elif defined(__HAIKU__)
  1117. char dir[B_PATH_NAME_LENGTH];
  1118. if (find_directory(B_USER_SETTINGS_DIRECTORY, -1, false, dir, sizeof(dir)) ==
  1119. B_OK) {
  1120. std::string fname = dir;
  1121. fname += "/cmake/packages/";
  1122. fname += Name;
  1123. this->LoadPackageRegistryDir(fname,
  1124. this->LabeledPaths[PathLabel::UserRegistry]);
  1125. }
  1126. #else
  1127. std::string dir;
  1128. if (cmSystemTools::GetEnv("HOME", dir)) {
  1129. dir += "/.cmake/packages/";
  1130. dir += this->Name;
  1131. this->LoadPackageRegistryDir(dir,
  1132. this->LabeledPaths[PathLabel::UserRegistry]);
  1133. }
  1134. #endif
  1135. }
  1136. void cmFindPackageCommand::FillPrefixesSystemRegistry()
  1137. {
  1138. if (this->NoSystemRegistry || this->NoDefaultPath) {
  1139. return;
  1140. }
  1141. #if defined(_WIN32) && !defined(__CYGWIN__)
  1142. this->LoadPackageRegistryWinSystem();
  1143. #endif
  1144. }
  1145. #if defined(_WIN32) && !defined(__CYGWIN__)
  1146. # include <windows.h>
  1147. // http://msdn.microsoft.com/en-us/library/aa384253%28v=vs.85%29.aspx
  1148. # if !defined(KEY_WOW64_32KEY)
  1149. # define KEY_WOW64_32KEY 0x0200
  1150. # endif
  1151. # if !defined(KEY_WOW64_64KEY)
  1152. # define KEY_WOW64_64KEY 0x0100
  1153. # endif
  1154. void cmFindPackageCommand::LoadPackageRegistryWinUser()
  1155. {
  1156. // HKEY_CURRENT_USER\\Software shares 32-bit and 64-bit views.
  1157. this->LoadPackageRegistryWin(true, 0,
  1158. this->LabeledPaths[PathLabel::UserRegistry]);
  1159. }
  1160. void cmFindPackageCommand::LoadPackageRegistryWinSystem()
  1161. {
  1162. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemRegistry];
  1163. // HKEY_LOCAL_MACHINE\\SOFTWARE has separate 32-bit and 64-bit views.
  1164. // Prefer the target platform view first.
  1165. if (this->Makefile->PlatformIs64Bit()) {
  1166. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  1167. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  1168. } else {
  1169. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  1170. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  1171. }
  1172. }
  1173. void cmFindPackageCommand::LoadPackageRegistryWin(bool user, unsigned int view,
  1174. cmSearchPath& outPaths)
  1175. {
  1176. std::wstring key = L"Software\\Kitware\\CMake\\Packages\\";
  1177. key += cmsys::Encoding::ToWide(this->Name);
  1178. std::set<std::wstring> bad;
  1179. HKEY hKey;
  1180. if (RegOpenKeyExW(user ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE, key.c_str(),
  1181. 0, KEY_QUERY_VALUE | view, &hKey) == ERROR_SUCCESS) {
  1182. DWORD valueType = REG_NONE;
  1183. wchar_t name[16383]; // RegEnumValue docs limit name to 32767 _bytes_
  1184. std::vector<wchar_t> data(512);
  1185. bool done = false;
  1186. DWORD index = 0;
  1187. while (!done) {
  1188. DWORD nameSize = static_cast<DWORD>(sizeof(name));
  1189. DWORD dataSize = static_cast<DWORD>(data.size() * sizeof(data[0]));
  1190. switch (RegEnumValueW(hKey, index, name, &nameSize, 0, &valueType,
  1191. (BYTE*)&data[0], &dataSize)) {
  1192. case ERROR_SUCCESS:
  1193. ++index;
  1194. if (valueType == REG_SZ) {
  1195. data[dataSize] = 0;
  1196. if (!this->CheckPackageRegistryEntry(
  1197. cmsys::Encoding::ToNarrow(&data[0]), outPaths)) {
  1198. // The entry is invalid.
  1199. bad.insert(name);
  1200. }
  1201. }
  1202. break;
  1203. case ERROR_MORE_DATA:
  1204. data.resize((dataSize + sizeof(data[0]) - 1) / sizeof(data[0]));
  1205. break;
  1206. case ERROR_NO_MORE_ITEMS:
  1207. default:
  1208. done = true;
  1209. break;
  1210. }
  1211. }
  1212. RegCloseKey(hKey);
  1213. }
  1214. // Remove bad values if possible.
  1215. if (user && !bad.empty() &&
  1216. RegOpenKeyExW(HKEY_CURRENT_USER, key.c_str(), 0, KEY_SET_VALUE | view,
  1217. &hKey) == ERROR_SUCCESS) {
  1218. for (std::wstring const& v : bad) {
  1219. RegDeleteValueW(hKey, v.c_str());
  1220. }
  1221. RegCloseKey(hKey);
  1222. }
  1223. }
  1224. #else
  1225. class cmFindPackageCommandHoldFile
  1226. {
  1227. const char* File;
  1228. public:
  1229. cmFindPackageCommandHoldFile(const char* f)
  1230. : File(f)
  1231. {
  1232. }
  1233. ~cmFindPackageCommandHoldFile()
  1234. {
  1235. if (this->File) {
  1236. cmSystemTools::RemoveFile(this->File);
  1237. }
  1238. }
  1239. cmFindPackageCommandHoldFile(const cmFindPackageCommandHoldFile&) = delete;
  1240. cmFindPackageCommandHoldFile& operator=(
  1241. const cmFindPackageCommandHoldFile&) = delete;
  1242. void Release() { this->File = nullptr; }
  1243. };
  1244. void cmFindPackageCommand::LoadPackageRegistryDir(std::string const& dir,
  1245. cmSearchPath& outPaths)
  1246. {
  1247. cmsys::Directory files;
  1248. if (!files.Load(dir)) {
  1249. return;
  1250. }
  1251. std::string fname;
  1252. for (unsigned long i = 0; i < files.GetNumberOfFiles(); ++i) {
  1253. fname = dir;
  1254. fname += "/";
  1255. fname += files.GetFile(i);
  1256. if (!cmSystemTools::FileIsDirectory(fname)) {
  1257. // Hold this file hostage until it behaves.
  1258. cmFindPackageCommandHoldFile holdFile(fname.c_str());
  1259. // Load the file.
  1260. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  1261. std::string fentry;
  1262. if (fin && cmSystemTools::GetLineFromStream(fin, fentry) &&
  1263. this->CheckPackageRegistryEntry(fentry, outPaths)) {
  1264. // The file references an existing package, so release it.
  1265. holdFile.Release();
  1266. }
  1267. }
  1268. }
  1269. // TODO: Wipe out the directory if it is empty.
  1270. }
  1271. #endif
  1272. bool cmFindPackageCommand::CheckPackageRegistryEntry(const std::string& fname,
  1273. cmSearchPath& outPaths)
  1274. {
  1275. // Parse the content of one package registry entry.
  1276. if (cmSystemTools::FileIsFullPath(fname)) {
  1277. // The first line in the stream is the full path to a file or
  1278. // directory containing the package.
  1279. if (cmSystemTools::FileExists(fname)) {
  1280. // The path exists. Look for the package here.
  1281. if (!cmSystemTools::FileIsDirectory(fname)) {
  1282. outPaths.AddPath(cmSystemTools::GetFilenamePath(fname));
  1283. } else {
  1284. outPaths.AddPath(fname);
  1285. }
  1286. return true;
  1287. }
  1288. // The path does not exist. Assume the stream content is
  1289. // associated with an old package that no longer exists, and
  1290. // delete it to keep the package registry clean.
  1291. return false;
  1292. }
  1293. // The first line in the stream is not the full path to a file or
  1294. // directory. Assume the stream content was created by a future
  1295. // version of CMake that uses a different format, and leave it.
  1296. return true;
  1297. }
  1298. void cmFindPackageCommand::FillPrefixesCMakeSystemVariable()
  1299. {
  1300. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeSystem];
  1301. paths.AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
  1302. paths.AddCMakePath("CMAKE_SYSTEM_FRAMEWORK_PATH");
  1303. paths.AddCMakePath("CMAKE_SYSTEM_APPBUNDLE_PATH");
  1304. }
  1305. void cmFindPackageCommand::FillPrefixesUserGuess()
  1306. {
  1307. cmSearchPath& paths = this->LabeledPaths[PathLabel::Guess];
  1308. for (std::string const& p : this->UserGuessArgs) {
  1309. paths.AddUserPath(p);
  1310. }
  1311. }
  1312. void cmFindPackageCommand::FillPrefixesUserHints()
  1313. {
  1314. cmSearchPath& paths = this->LabeledPaths[PathLabel::Hints];
  1315. for (std::string const& p : this->UserHintsArgs) {
  1316. paths.AddUserPath(p);
  1317. }
  1318. }
  1319. bool cmFindPackageCommand::SearchDirectory(std::string const& dir)
  1320. {
  1321. assert(!dir.empty() && dir.back() == '/');
  1322. // Check each path suffix on this directory.
  1323. for (std::string const& s : this->SearchPathSuffixes) {
  1324. std::string d = dir;
  1325. if (!s.empty()) {
  1326. d += s;
  1327. d += "/";
  1328. }
  1329. if (this->CheckDirectory(d)) {
  1330. return true;
  1331. }
  1332. }
  1333. return false;
  1334. }
  1335. bool cmFindPackageCommand::CheckDirectory(std::string const& dir)
  1336. {
  1337. assert(!dir.empty() && dir.back() == '/');
  1338. // Look for the file in this directory.
  1339. std::string d = dir.substr(0, dir.size() - 1);
  1340. if (this->FindConfigFile(d, this->FileFound)) {
  1341. // Remove duplicate slashes.
  1342. cmSystemTools::ConvertToUnixSlashes(this->FileFound);
  1343. return true;
  1344. }
  1345. return false;
  1346. }
  1347. bool cmFindPackageCommand::FindConfigFile(std::string const& dir,
  1348. std::string& file)
  1349. {
  1350. if (this->IgnoredPaths.count(dir)) {
  1351. return false;
  1352. }
  1353. for (std::string const& c : this->Configs) {
  1354. file = dir;
  1355. file += "/";
  1356. file += c;
  1357. if (this->DebugMode) {
  1358. fprintf(stderr, "Checking file [%s]\n", file.c_str());
  1359. }
  1360. if (cmSystemTools::FileExists(file, true) && this->CheckVersion(file)) {
  1361. // Allow resolving symlinks when the config file is found through a link
  1362. if (this->UseRealPath) {
  1363. file = cmSystemTools::GetRealPath(file);
  1364. }
  1365. return true;
  1366. }
  1367. }
  1368. return false;
  1369. }
  1370. bool cmFindPackageCommand::CheckVersion(std::string const& config_file)
  1371. {
  1372. bool result = false; // by default, assume the version is not ok.
  1373. bool haveResult = false;
  1374. std::string version = "unknown";
  1375. // Get the filename without the .cmake extension.
  1376. std::string::size_type pos = config_file.rfind('.');
  1377. std::string version_file_base = config_file.substr(0, pos);
  1378. // Look for foo-config-version.cmake
  1379. std::string version_file = version_file_base;
  1380. version_file += "-version.cmake";
  1381. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  1382. result = this->CheckVersionFile(version_file, version);
  1383. haveResult = true;
  1384. }
  1385. // Look for fooConfigVersion.cmake
  1386. version_file = version_file_base;
  1387. version_file += "Version.cmake";
  1388. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  1389. result = this->CheckVersionFile(version_file, version);
  1390. haveResult = true;
  1391. }
  1392. // If no version was requested a versionless package is acceptable.
  1393. if (!haveResult && this->Version.empty()) {
  1394. result = true;
  1395. }
  1396. ConfigFileInfo configFileInfo;
  1397. configFileInfo.filename = config_file;
  1398. configFileInfo.version = version;
  1399. this->ConsideredConfigs.push_back(std::move(configFileInfo));
  1400. return result;
  1401. }
  1402. bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file,
  1403. std::string& result_version)
  1404. {
  1405. // The version file will be loaded in an isolated scope.
  1406. cmMakefile::ScopePushPop varScope(this->Makefile);
  1407. cmMakefile::PolicyPushPop polScope(this->Makefile);
  1408. static_cast<void>(varScope);
  1409. static_cast<void>(polScope);
  1410. // Clear the output variables.
  1411. this->Makefile->RemoveDefinition("PACKAGE_VERSION");
  1412. this->Makefile->RemoveDefinition("PACKAGE_VERSION_UNSUITABLE");
  1413. this->Makefile->RemoveDefinition("PACKAGE_VERSION_COMPATIBLE");
  1414. this->Makefile->RemoveDefinition("PACKAGE_VERSION_EXACT");
  1415. // Set the input variables.
  1416. this->Makefile->AddDefinition("PACKAGE_FIND_NAME", this->Name.c_str());
  1417. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION", this->Version.c_str());
  1418. char buf[64];
  1419. sprintf(buf, "%u", this->VersionMajor);
  1420. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MAJOR", buf);
  1421. sprintf(buf, "%u", this->VersionMinor);
  1422. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MINOR", buf);
  1423. sprintf(buf, "%u", this->VersionPatch);
  1424. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_PATCH", buf);
  1425. sprintf(buf, "%u", this->VersionTweak);
  1426. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_TWEAK", buf);
  1427. sprintf(buf, "%u", this->VersionCount);
  1428. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_COUNT", buf);
  1429. // Load the version check file. Pass NoPolicyScope because we do
  1430. // our own policy push/pop independent of CMP0011.
  1431. bool suitable = false;
  1432. if (this->ReadListFile(version_file, NoPolicyScope)) {
  1433. // Check the output variables.
  1434. bool okay = this->Makefile->IsOn("PACKAGE_VERSION_EXACT");
  1435. bool unsuitable = this->Makefile->IsOn("PACKAGE_VERSION_UNSUITABLE");
  1436. if (!okay && !this->VersionExact) {
  1437. okay = this->Makefile->IsOn("PACKAGE_VERSION_COMPATIBLE");
  1438. }
  1439. // The package is suitable if the version is okay and not
  1440. // explicitly unsuitable.
  1441. suitable = !unsuitable && (okay || this->Version.empty());
  1442. if (suitable) {
  1443. // Get the version found.
  1444. this->VersionFound =
  1445. this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  1446. // Try to parse the version number and store the results that were
  1447. // successfully parsed.
  1448. unsigned int parsed_major;
  1449. unsigned int parsed_minor;
  1450. unsigned int parsed_patch;
  1451. unsigned int parsed_tweak;
  1452. this->VersionFoundCount =
  1453. sscanf(this->VersionFound.c_str(), "%u.%u.%u.%u", &parsed_major,
  1454. &parsed_minor, &parsed_patch, &parsed_tweak);
  1455. switch (this->VersionFoundCount) {
  1456. case 4:
  1457. this->VersionFoundTweak = parsed_tweak;
  1458. CM_FALLTHROUGH;
  1459. case 3:
  1460. this->VersionFoundPatch = parsed_patch;
  1461. CM_FALLTHROUGH;
  1462. case 2:
  1463. this->VersionFoundMinor = parsed_minor;
  1464. CM_FALLTHROUGH;
  1465. case 1:
  1466. this->VersionFoundMajor = parsed_major;
  1467. CM_FALLTHROUGH;
  1468. default:
  1469. break;
  1470. }
  1471. }
  1472. }
  1473. result_version = this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  1474. if (result_version.empty()) {
  1475. result_version = "unknown";
  1476. }
  1477. // Succeed if the version is suitable.
  1478. return suitable;
  1479. }
  1480. void cmFindPackageCommand::StoreVersionFound()
  1481. {
  1482. // Store the whole version string.
  1483. std::string ver = this->Name;
  1484. ver += "_VERSION";
  1485. if (this->VersionFound.empty()) {
  1486. this->Makefile->RemoveDefinition(ver);
  1487. } else {
  1488. this->Makefile->AddDefinition(ver, this->VersionFound.c_str());
  1489. }
  1490. // Store the version components.
  1491. char buf[64];
  1492. sprintf(buf, "%u", this->VersionFoundMajor);
  1493. this->Makefile->AddDefinition(ver + "_MAJOR", buf);
  1494. sprintf(buf, "%u", this->VersionFoundMinor);
  1495. this->Makefile->AddDefinition(ver + "_MINOR", buf);
  1496. sprintf(buf, "%u", this->VersionFoundPatch);
  1497. this->Makefile->AddDefinition(ver + "_PATCH", buf);
  1498. sprintf(buf, "%u", this->VersionFoundTweak);
  1499. this->Makefile->AddDefinition(ver + "_TWEAK", buf);
  1500. sprintf(buf, "%u", this->VersionFoundCount);
  1501. this->Makefile->AddDefinition(ver + "_COUNT", buf);
  1502. }
  1503. class cmFileListGeneratorBase
  1504. {
  1505. public:
  1506. virtual ~cmFileListGeneratorBase() = default;
  1507. protected:
  1508. bool Consider(std::string const& fullPath, cmFileList& listing);
  1509. private:
  1510. bool Search(cmFileList&);
  1511. virtual bool Search(std::string const& parent, cmFileList&) = 0;
  1512. virtual std::unique_ptr<cmFileListGeneratorBase> Clone() const = 0;
  1513. friend class cmFileList;
  1514. cmFileListGeneratorBase* SetNext(cmFileListGeneratorBase const& next);
  1515. std::unique_ptr<cmFileListGeneratorBase> Next;
  1516. };
  1517. class cmFileList
  1518. {
  1519. public:
  1520. virtual ~cmFileList() = default;
  1521. cmFileList& operator/(cmFileListGeneratorBase const& rhs)
  1522. {
  1523. if (this->Last) {
  1524. this->Last = this->Last->SetNext(rhs);
  1525. } else {
  1526. this->First = rhs.Clone();
  1527. this->Last = this->First.get();
  1528. }
  1529. return *this;
  1530. }
  1531. bool Search()
  1532. {
  1533. if (this->First) {
  1534. return this->First->Search(*this);
  1535. }
  1536. return false;
  1537. }
  1538. private:
  1539. virtual bool Visit(std::string const& fullPath) = 0;
  1540. friend class cmFileListGeneratorBase;
  1541. std::unique_ptr<cmFileListGeneratorBase> First;
  1542. cmFileListGeneratorBase* Last = nullptr;
  1543. };
  1544. class cmFindPackageFileList : public cmFileList
  1545. {
  1546. public:
  1547. cmFindPackageFileList(cmFindPackageCommand* fpc, bool use_suffixes = true)
  1548. : FPC(fpc)
  1549. , UseSuffixes(use_suffixes)
  1550. {
  1551. }
  1552. private:
  1553. bool Visit(std::string const& fullPath) override
  1554. {
  1555. if (this->UseSuffixes) {
  1556. return this->FPC->SearchDirectory(fullPath);
  1557. }
  1558. return this->FPC->CheckDirectory(fullPath);
  1559. }
  1560. cmFindPackageCommand* FPC;
  1561. bool UseSuffixes;
  1562. };
  1563. bool cmFileListGeneratorBase::Search(cmFileList& listing)
  1564. {
  1565. return this->Search("", listing);
  1566. }
  1567. cmFileListGeneratorBase* cmFileListGeneratorBase::SetNext(
  1568. cmFileListGeneratorBase const& next)
  1569. {
  1570. this->Next = next.Clone();
  1571. return this->Next.get();
  1572. }
  1573. bool cmFileListGeneratorBase::Consider(std::string const& fullPath,
  1574. cmFileList& listing)
  1575. {
  1576. if (this->Next) {
  1577. return this->Next->Search(fullPath + "/", listing);
  1578. }
  1579. return listing.Visit(fullPath + "/");
  1580. }
  1581. class cmFileListGeneratorFixed : public cmFileListGeneratorBase
  1582. {
  1583. public:
  1584. cmFileListGeneratorFixed(std::string str)
  1585. : String(std::move(str))
  1586. {
  1587. }
  1588. cmFileListGeneratorFixed(cmFileListGeneratorFixed const& r)
  1589. : String(r.String)
  1590. {
  1591. }
  1592. private:
  1593. std::string String;
  1594. bool Search(std::string const& parent, cmFileList& lister) override
  1595. {
  1596. std::string fullPath = parent + this->String;
  1597. return this->Consider(fullPath, lister);
  1598. }
  1599. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1600. {
  1601. std::unique_ptr<cmFileListGeneratorBase> g(
  1602. new cmFileListGeneratorFixed(*this));
  1603. return g;
  1604. }
  1605. };
  1606. class cmFileListGeneratorEnumerate : public cmFileListGeneratorBase
  1607. {
  1608. public:
  1609. cmFileListGeneratorEnumerate(std::vector<std::string> const& v)
  1610. : Vector(v)
  1611. {
  1612. }
  1613. cmFileListGeneratorEnumerate(cmFileListGeneratorEnumerate const& r)
  1614. : Vector(r.Vector)
  1615. {
  1616. }
  1617. private:
  1618. std::vector<std::string> const& Vector;
  1619. bool Search(std::string const& parent, cmFileList& lister) override
  1620. {
  1621. for (std::string const& i : this->Vector) {
  1622. if (this->Consider(parent + i, lister)) {
  1623. return true;
  1624. }
  1625. }
  1626. return false;
  1627. }
  1628. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1629. {
  1630. std::unique_ptr<cmFileListGeneratorBase> g(
  1631. new cmFileListGeneratorEnumerate(*this));
  1632. return g;
  1633. }
  1634. };
  1635. class cmFileListGeneratorProject : public cmFileListGeneratorBase
  1636. {
  1637. public:
  1638. cmFileListGeneratorProject(std::vector<std::string> const& names,
  1639. cmFindPackageCommand::SortOrderType so,
  1640. cmFindPackageCommand::SortDirectionType sd)
  1641. : Names(names)
  1642. {
  1643. this->SetSort(so, sd);
  1644. }
  1645. cmFileListGeneratorProject(cmFileListGeneratorProject const& r)
  1646. : Names(r.Names)
  1647. {
  1648. this->SetSort(r.SortOrder, r.SortDirection);
  1649. }
  1650. void SetSort(cmFindPackageCommand::SortOrderType o,
  1651. cmFindPackageCommand::SortDirectionType d)
  1652. {
  1653. SortOrder = o;
  1654. SortDirection = d;
  1655. }
  1656. protected:
  1657. // sort parameters
  1658. cmFindPackageCommand::SortOrderType SortOrder;
  1659. cmFindPackageCommand::SortDirectionType SortDirection;
  1660. private:
  1661. std::vector<std::string> const& Names;
  1662. bool Search(std::string const& parent, cmFileList& lister) override
  1663. {
  1664. // Construct a list of matches.
  1665. std::vector<std::string> matches;
  1666. cmsys::Directory d;
  1667. d.Load(parent);
  1668. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  1669. const char* fname = d.GetFile(i);
  1670. if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
  1671. continue;
  1672. }
  1673. for (std::string const& n : this->Names) {
  1674. if (cmsysString_strncasecmp(fname, n.c_str(), n.length()) == 0) {
  1675. matches.emplace_back(fname);
  1676. }
  1677. }
  1678. }
  1679. // before testing the matches check if there is a specific sorting order to
  1680. // perform
  1681. if (this->SortOrder != cmFindPackageCommand::None) {
  1682. cmFindPackageCommand::Sort(matches.begin(), matches.end(), SortOrder,
  1683. SortDirection);
  1684. }
  1685. for (std::string const& i : matches) {
  1686. if (this->Consider(parent + i, lister)) {
  1687. return true;
  1688. }
  1689. }
  1690. return false;
  1691. }
  1692. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1693. {
  1694. std::unique_ptr<cmFileListGeneratorBase> g(
  1695. new cmFileListGeneratorProject(*this));
  1696. return g;
  1697. }
  1698. };
  1699. class cmFileListGeneratorMacProject : public cmFileListGeneratorBase
  1700. {
  1701. public:
  1702. cmFileListGeneratorMacProject(std::vector<std::string> const& names,
  1703. const char* ext)
  1704. : Names(names)
  1705. , Extension(ext)
  1706. {
  1707. }
  1708. cmFileListGeneratorMacProject(cmFileListGeneratorMacProject const& r)
  1709. : Names(r.Names)
  1710. , Extension(r.Extension)
  1711. {
  1712. }
  1713. private:
  1714. std::vector<std::string> const& Names;
  1715. std::string Extension;
  1716. bool Search(std::string const& parent, cmFileList& lister) override
  1717. {
  1718. // Construct a list of matches.
  1719. std::vector<std::string> matches;
  1720. cmsys::Directory d;
  1721. d.Load(parent);
  1722. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  1723. const char* fname = d.GetFile(i);
  1724. if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
  1725. continue;
  1726. }
  1727. for (std::string name : this->Names) {
  1728. name += this->Extension;
  1729. if (cmsysString_strcasecmp(fname, name.c_str()) == 0) {
  1730. matches.emplace_back(fname);
  1731. }
  1732. }
  1733. }
  1734. for (std::string const& i : matches) {
  1735. if (this->Consider(parent + i, lister)) {
  1736. return true;
  1737. }
  1738. }
  1739. return false;
  1740. }
  1741. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1742. {
  1743. std::unique_ptr<cmFileListGeneratorBase> g(
  1744. new cmFileListGeneratorMacProject(*this));
  1745. return g;
  1746. }
  1747. };
  1748. class cmFileListGeneratorCaseInsensitive : public cmFileListGeneratorBase
  1749. {
  1750. public:
  1751. cmFileListGeneratorCaseInsensitive(std::string str)
  1752. : String(std::move(str))
  1753. {
  1754. }
  1755. cmFileListGeneratorCaseInsensitive(
  1756. cmFileListGeneratorCaseInsensitive const& r)
  1757. : String(r.String)
  1758. {
  1759. }
  1760. private:
  1761. std::string String;
  1762. bool Search(std::string const& parent, cmFileList& lister) override
  1763. {
  1764. // Look for matching files.
  1765. std::vector<std::string> matches;
  1766. cmsys::Directory d;
  1767. d.Load(parent);
  1768. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  1769. const char* fname = d.GetFile(i);
  1770. if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
  1771. continue;
  1772. }
  1773. if (cmsysString_strcasecmp(fname, this->String.c_str()) == 0) {
  1774. if (this->Consider(parent + fname, lister)) {
  1775. return true;
  1776. }
  1777. }
  1778. }
  1779. return false;
  1780. }
  1781. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1782. {
  1783. std::unique_ptr<cmFileListGeneratorBase> g(
  1784. new cmFileListGeneratorCaseInsensitive(*this));
  1785. return g;
  1786. }
  1787. };
  1788. class cmFileListGeneratorGlob : public cmFileListGeneratorBase
  1789. {
  1790. public:
  1791. cmFileListGeneratorGlob(std::string str)
  1792. : Pattern(std::move(str))
  1793. {
  1794. }
  1795. cmFileListGeneratorGlob(cmFileListGeneratorGlob const& r)
  1796. : Pattern(r.Pattern)
  1797. {
  1798. }
  1799. private:
  1800. std::string Pattern;
  1801. bool Search(std::string const& parent, cmFileList& lister) override
  1802. {
  1803. // Glob the set of matching files.
  1804. std::string expr = parent;
  1805. expr += this->Pattern;
  1806. cmsys::Glob g;
  1807. if (!g.FindFiles(expr)) {
  1808. return false;
  1809. }
  1810. std::vector<std::string> const& files = g.GetFiles();
  1811. // Look for directories among the matches.
  1812. for (std::string const& f : files) {
  1813. if (cmSystemTools::FileIsDirectory(f)) {
  1814. if (this->Consider(f, lister)) {
  1815. return true;
  1816. }
  1817. }
  1818. }
  1819. return false;
  1820. }
  1821. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1822. {
  1823. return cm::make_unique<cmFileListGeneratorGlob>(*this);
  1824. }
  1825. };
  1826. bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
  1827. {
  1828. assert(!prefix_in.empty() && prefix_in.back() == '/');
  1829. if (this->DebugMode) {
  1830. fprintf(stderr, "Checking prefix [%s]\n", prefix_in.c_str());
  1831. }
  1832. // Skip this if the prefix does not exist.
  1833. if (!cmSystemTools::FileIsDirectory(prefix_in)) {
  1834. return false;
  1835. }
  1836. // PREFIX/ (useful on windows or in build trees)
  1837. if (this->SearchDirectory(prefix_in)) {
  1838. return true;
  1839. }
  1840. // Strip the trailing slash because the path generator is about to
  1841. // add one.
  1842. std::string prefix = prefix_in.substr(0, prefix_in.size() - 1);
  1843. // PREFIX/(cmake|CMake)/ (useful on windows or in build trees)
  1844. {
  1845. cmFindPackageFileList lister(this);
  1846. lister / cmFileListGeneratorFixed(prefix) /
  1847. cmFileListGeneratorCaseInsensitive("cmake");
  1848. if (lister.Search()) {
  1849. return true;
  1850. }
  1851. }
  1852. // PREFIX/(Foo|foo|FOO).*/
  1853. {
  1854. cmFindPackageFileList lister(this);
  1855. lister / cmFileListGeneratorFixed(prefix) /
  1856. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1857. this->SortDirection);
  1858. if (lister.Search()) {
  1859. return true;
  1860. }
  1861. }
  1862. // PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/
  1863. {
  1864. cmFindPackageFileList lister(this);
  1865. lister / cmFileListGeneratorFixed(prefix) /
  1866. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1867. this->SortDirection) /
  1868. cmFileListGeneratorCaseInsensitive("cmake");
  1869. if (lister.Search()) {
  1870. return true;
  1871. }
  1872. }
  1873. // Construct list of common install locations (lib and share).
  1874. std::vector<std::string> common;
  1875. if (!this->LibraryArchitecture.empty()) {
  1876. common.push_back("lib/" + this->LibraryArchitecture);
  1877. }
  1878. if (this->UseLib32Paths) {
  1879. common.emplace_back("lib32");
  1880. }
  1881. if (this->UseLib64Paths) {
  1882. common.emplace_back("lib64");
  1883. }
  1884. if (this->UseLibx32Paths) {
  1885. common.emplace_back("libx32");
  1886. }
  1887. common.emplace_back("lib");
  1888. common.emplace_back("share");
  1889. // PREFIX/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  1890. {
  1891. cmFindPackageFileList lister(this);
  1892. lister / cmFileListGeneratorFixed(prefix) /
  1893. cmFileListGeneratorEnumerate(common) /
  1894. cmFileListGeneratorFixed("cmake") /
  1895. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1896. this->SortDirection);
  1897. if (lister.Search()) {
  1898. return true;
  1899. }
  1900. }
  1901. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  1902. {
  1903. cmFindPackageFileList lister(this);
  1904. lister / cmFileListGeneratorFixed(prefix) /
  1905. cmFileListGeneratorEnumerate(common) /
  1906. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1907. this->SortDirection);
  1908. if (lister.Search()) {
  1909. return true;
  1910. }
  1911. }
  1912. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  1913. {
  1914. cmFindPackageFileList lister(this);
  1915. lister / cmFileListGeneratorFixed(prefix) /
  1916. cmFileListGeneratorEnumerate(common) /
  1917. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1918. this->SortDirection) /
  1919. cmFileListGeneratorCaseInsensitive("cmake");
  1920. if (lister.Search()) {
  1921. return true;
  1922. }
  1923. }
  1924. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  1925. {
  1926. cmFindPackageFileList lister(this);
  1927. lister / cmFileListGeneratorFixed(prefix) /
  1928. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1929. this->SortDirection) /
  1930. cmFileListGeneratorEnumerate(common) /
  1931. cmFileListGeneratorFixed("cmake") /
  1932. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1933. this->SortDirection);
  1934. if (lister.Search()) {
  1935. return true;
  1936. }
  1937. }
  1938. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  1939. {
  1940. cmFindPackageFileList lister(this);
  1941. lister / cmFileListGeneratorFixed(prefix) /
  1942. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1943. this->SortDirection) /
  1944. cmFileListGeneratorEnumerate(common) /
  1945. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1946. this->SortDirection);
  1947. if (lister.Search()) {
  1948. return true;
  1949. }
  1950. }
  1951. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  1952. {
  1953. cmFindPackageFileList lister(this);
  1954. lister / cmFileListGeneratorFixed(prefix) /
  1955. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1956. this->SortDirection) /
  1957. cmFileListGeneratorEnumerate(common) /
  1958. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1959. this->SortDirection) /
  1960. cmFileListGeneratorCaseInsensitive("cmake");
  1961. if (lister.Search()) {
  1962. return true;
  1963. }
  1964. }
  1965. return false;
  1966. }
  1967. bool cmFindPackageCommand::SearchFrameworkPrefix(std::string const& prefix_in)
  1968. {
  1969. assert(!prefix_in.empty() && prefix_in.back() == '/');
  1970. if (this->DebugMode) {
  1971. fprintf(stderr, "Checking framework prefix [%s]\n", prefix_in.c_str());
  1972. }
  1973. // Strip the trailing slash because the path generator is about to
  1974. // add one.
  1975. std::string prefix = prefix_in.substr(0, prefix_in.size() - 1);
  1976. // <prefix>/Foo.framework/Resources/
  1977. {
  1978. cmFindPackageFileList lister(this);
  1979. lister / cmFileListGeneratorFixed(prefix) /
  1980. cmFileListGeneratorMacProject(this->Names, ".framework") /
  1981. cmFileListGeneratorFixed("Resources");
  1982. if (lister.Search()) {
  1983. return true;
  1984. }
  1985. }
  1986. // <prefix>/Foo.framework/Resources/CMake/
  1987. {
  1988. cmFindPackageFileList lister(this);
  1989. lister / cmFileListGeneratorFixed(prefix) /
  1990. cmFileListGeneratorMacProject(this->Names, ".framework") /
  1991. cmFileListGeneratorFixed("Resources") /
  1992. cmFileListGeneratorCaseInsensitive("cmake");
  1993. if (lister.Search()) {
  1994. return true;
  1995. }
  1996. }
  1997. // <prefix>/Foo.framework/Versions/*/Resources/
  1998. {
  1999. cmFindPackageFileList lister(this);
  2000. lister / cmFileListGeneratorFixed(prefix) /
  2001. cmFileListGeneratorMacProject(this->Names, ".framework") /
  2002. cmFileListGeneratorFixed("Versions") /
  2003. cmFileListGeneratorGlob("*/Resources");
  2004. if (lister.Search()) {
  2005. return true;
  2006. }
  2007. }
  2008. // <prefix>/Foo.framework/Versions/*/Resources/CMake/
  2009. {
  2010. cmFindPackageFileList lister(this);
  2011. lister / cmFileListGeneratorFixed(prefix) /
  2012. cmFileListGeneratorMacProject(this->Names, ".framework") /
  2013. cmFileListGeneratorFixed("Versions") /
  2014. cmFileListGeneratorGlob("*/Resources") /
  2015. cmFileListGeneratorCaseInsensitive("cmake");
  2016. if (lister.Search()) {
  2017. return true;
  2018. }
  2019. }
  2020. return false;
  2021. }
  2022. bool cmFindPackageCommand::SearchAppBundlePrefix(std::string const& prefix_in)
  2023. {
  2024. assert(!prefix_in.empty() && prefix_in.back() == '/');
  2025. if (this->DebugMode) {
  2026. fprintf(stderr, "Checking bundle prefix [%s]\n", prefix_in.c_str());
  2027. }
  2028. // Strip the trailing slash because the path generator is about to
  2029. // add one.
  2030. std::string prefix = prefix_in.substr(0, prefix_in.size() - 1);
  2031. // <prefix>/Foo.app/Contents/Resources
  2032. {
  2033. cmFindPackageFileList lister(this);
  2034. lister / cmFileListGeneratorFixed(prefix) /
  2035. cmFileListGeneratorMacProject(this->Names, ".app") /
  2036. cmFileListGeneratorFixed("Contents/Resources");
  2037. if (lister.Search()) {
  2038. return true;
  2039. }
  2040. }
  2041. // <prefix>/Foo.app/Contents/Resources/CMake
  2042. {
  2043. cmFindPackageFileList lister(this);
  2044. lister / cmFileListGeneratorFixed(prefix) /
  2045. cmFileListGeneratorMacProject(this->Names, ".app") /
  2046. cmFileListGeneratorFixed("Contents/Resources") /
  2047. cmFileListGeneratorCaseInsensitive("cmake");
  2048. if (lister.Search()) {
  2049. return true;
  2050. }
  2051. }
  2052. return false;
  2053. }
  2054. // TODO: Debug cmsys::Glob double slash problem.