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