cmFindPackageCommand.cxx 71 KB

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