cmFindPackageCommand.cxx 70 KB

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